Spire.Office Knowledgebase Page 3 | E-iceblue

Spire.OfficeJS is a powerful front-end JavaScript library that enables users to edit, preview, and process Office documents directly in a web browser—without plugins and without installing local tools such as Microsoft Office or WPS.

This article explains how to use Spire.OfficeJS in a native JavaScript environment.

Spire.OfficeJS consists of four modules:

  • Spire.WordJS: Provides preview and editing capabilities for Word documents, with full compatibility with Microsoft Word and WPS formats, such as .doc, .docx, .wps, and .wpt.
  • Spire.ExcelJS: Enables preview and editing of Excel documents, including formats such as .xls, .xlsx, .et, and .ett.
  • Spire.PresentationJS: Supports preview and editing of PowerPoint documents, including .ppt and .pptx.
  • Spire.PDFJS: Provides preview functionality for PDF documents.

Table of Contents

Preparation

Spire.OfficeJS is powered by a web service. To use it in a native JavaScript environment, you must first start the web service.

The service is launched using scripts included in the product package, with the default service port set to 8001.

Step 1. Download and Extract the Installation Package

Download the Spire.OfficeJS package for your operating system, and extract it to a local directory.

Step 2. Start the Web Service

  • Windows

In the extracted product directory, run the run_servers.bat file. The terminal output will be similar to the following:

Windows Terminal Output

Note: Port 3000 is used by the sample document management system. By default, you can access it in a browser at localhost:3000 or 127.0.0.1:3000 for testing.

  • Linux (x86_64)

Run the run_servers.sh file in the extracted product directory using the command sh run_servers.sh start (to stop the service, use sh run_servers.sh stop; to restart the service, use sh run_servers.sh restart).

The terminal output is shown below:

Linux Terminal Output

Step 3. Configure the Service Address

By default, the service uses 127.0.0.1. You can modify the baseUrl value in the example\config\default.json file to a domain name or an actual IP address, so that the service can be accessed via a domain or IP address.

After making the change, restart the service for the configuration to take effect.

Modify baseUrl

Now, the client can access the sample system using the configured IP address or domain name, for example: 192.168.3.127:3000

System Sample

JavaScript Integration Examples:

  • Browser Preview Integration (HTML):

Browser Preview

Script file:

To help you get started quickly, you can download the complete HTML example file using the link below and open it directly in your browser:

Demo Download

Click to download

  • Parameter Description:
Parameter Example Description Value
fileAttrs File Configuration Object
fileInfo File Information Object
name File Name Optional Optional
ext Document Name docx,xlsx,pptx
primary Document Unique Identifier Optional
creator Document Creator Optional
createTime Document Creation Time Optional
sourceUrl Document URL Required. Must be accessible and have the appropriate access permissions.
createUrl Template Document URL Optional
user User Configuration Object
id User ID Optional
name User Name Optional
editorAttrs Editor Configuration Object
editorMode Edit Mode Optional. Accepts 'edit' (edit) or 'view' (view). Default is 'edit'. Optional. Accepts 'edit' (edit) or 'view' (view). Default is 'edit'.
editorWidth Width Optional. Default value is 100%.
editorHeight Height Optional. Default value is 100%.
editorType Editor Type Optional. If not specified, the editor type is determined automatically based on the file type. Must be set to document, spreadsheet, or presentation.
platform Editor Platform Type Required. Accepts 'desktop' (desktop view), 'mobile' (mobile view), or 'embedded' (embedded view). Must be set to one of: desktop, mobile, or embedded.
viewLanguage UI Language Optional. Accepts "en" or "zh". If not specified, the browser’s default language is used.
isReadOnly Read-Only Mode Default is false, allowing the document to be edited. When set to true, the document is read-only.
canChat Chat Enabled Default is true. When set to false, chat is disabled.
canComment Comments Enabled Default is true. When set to false, comments are disabled.
canReview Track Changes Enabled Default is true. When set to false, track changes is disabled.
canDownload Download Allowed Default is true, allowing downloads. When set to false, downloading is not allowed.
canEdit Edit Allowed Default is true, allowing editing. When set to false, editing is not allowed.
canForcesave Force Save Enabled Default is true. When set to false, force save is disabled.
embedded Embedded View Configuration Object Includes saveUrl, embedUrl, shareUrl, and toolbarDocked, used to control saving, sharing, and toolbar display in embedded mode.
saveUrl Embedded Document Save URL Default is empty. Can be set to a URL used to save edited content.
embedUrl Embedded Document Access URL Default is empty. Can be set to a URL used to open the document directly.
shareUrl Embedded Document Share URL Default is empty. Can be set to a URL used to share the document.
toolbarDocked Toolbar Dock Position Default is "top". Accepts "top" or "bottom".
events Events
plugins Editor Plugin Configuration Object Default is empty. Used to extend editor functionality.
pluginsData Plugin Data Array Default is empty. Plugins can be added as needed.
useWebAssemblyDoc Enable WebAssembly for Word Documents Default is true, allowing Word documents to be processed in the browser. When set to false, WebAssembly support is disabled.
spireDocJsLicense Word WebAssembly License File URL Default is empty. Used to activate the WebAssembly functionality.
useWebAssemblyExcel Enable WebAssembly for Excel Documents Default is true, allowing Excel documents to be processed in the browser. When set to false, WebAssembly support is disabled.
spireXlsJsLicense Excel WebAssembly License File URL Default is empty. Used to activate the WebAssembly functionality.
useWebAssemblyPpt Enable WebAssembly for PowerPoint Documents Default is true, allowing PowerPoint documents to be processed in the browser. When set to false, WebAssembly support is disabled.
spirePresentationJsLicense PowerPoint WebAssembly License File URL Default is empty. Used to activate the WebAssembly functionality.
useWebAssemblyPdf Enable WebAssembly for PDF Documents Default is true, allowing PDF documents to be processed in the browser. When set to false, WebAssembly support is disabled.
spirePdfJsLicense PDF WebAssembly License File Default is empty. Used to activate the WebAssembly functionality.
spireOfficeJsLicense OfficeJS License File Default is empty. Used to activate all online document editing features.
serverless Serverless Mode Configuration Object Includes useServerless, baseUrl, and fileData, allowing the front end to upload, edit, and download documents directly.
useSeverless Enable Serverless Mode Default is true. When enabled, the front end can operate on documents directly. When set to false, a server-side service is required.
baseUrl Service URL in Serverless Mode Default is empty. Must be set to the deployed server IP address and port.
fileData Document Data Default is empty. Stores the uploaded file data on the front end and is used to initialize the editor.

Note: Applying a license removes the default watermark and unlocks all features. If you need a license file, please feel free to contact us at any time.

Frequently Asked Questions

During the deployment and integration of Spire.OfficeJS, you may encounter certain issues. The table below lists some common problems along with their solutions for your reference. If you have any additional questions, please contact our technical support team.

Issue Cause Solution
Unable to access the service in the browser Service not started / Required ports not open Verify that the service is running and ensure ports 3000 and 8001 are open
Page loads but displays a blank screen Browser cache contains outdated resources Clear the browser cache or reopen the page in private/incognito mode
JavaScript file fails to load Incorrect IP address or port Check whether the SpireCloudEditor.js script URL is correct
File upload fails baseUrl is not configured with the actual deployment address Update the configuration file and restart the service
Unable to execute the script on Linux Insufficient script permissions Run chmod +x run_servers.sh to grant execute permissions

Summary

At this point, you have successfully completed the deployment and integration of Spire.OfficeJS. Your system can now view and edit documents online directly in the browser, without requiring client-side installations or additional development environments.

If you would like to explore more advanced usage scenarios or learn how to integrate Spire.OfficeJS into different types of applications, please refer to the related documentation or contact our team for further guidance.

DataGrid/GridView to Excel Export with C#

Exporting tabular data from UI controls to Excel is a common requirement in C# applications. In both WinForms and ASP.NET projects, users often need to take the data currently displayed in a DataGrid, DataGridView, or GridView and export it to an Excel file for reporting, sharing, or further processing.

In real-world scenarios, exported Excel files are rarely used as raw data only. Readable layouts, header styles, column widths, and number formats are usually expected as part of the export result.

This article demonstrates how to export DataGridView and GridView/DataGrid data to Excel in C# using Spire.XLS for .NET, without relying on Microsoft Office Interop. The solution focuses on exporting displayed data accurately, keeping the implementation clean, and applying Excel formatting in a consistent and reusable way.

Table of Contents


Advantages of Programmatic Excel Export in C#

While Microsoft Office Interop can generate Excel files, using a programmatic approach in C# provides clear benefits for exporting data from DataGrid, DataGridView, or GridView:

  • Does not require Microsoft Excel to be installed on the machine
  • Suitable for server-side or cloud environments
  • Maintains high performance even with large datasets
  • Simplifies automation and background export scenarios

By exporting data directly via code, developers can create reliable, maintainable, and scalable Excel exports that work consistently across different application types.


Core Concept: Export Displayed Data via a DataTable

Although DataGrid, DataGridView, and GridView are UI controls, they serve the same fundamental purpose: displaying structured data in rows and columns. Attempting to export these controls directly often leads to UI-dependent logic and maintenance challenges.

A more reliable and reusable workflow is:

Displayed UI data → DataTable → Excel file

In this design:

  • The DataTable represents exactly what the user sees
  • The Excel export logic remains independent of the UI layer
  • The same approach works for WinForms and ASP.NET applications
  • Formatting and layout can be applied at the Excel level

The DataTable acts as a clean intermediate structure rather than the final export target, and using Spire.XLS for .NET, DataTable can be easily exported to a well-formatted Excel file.


Step 1: Extract Displayed Data into a DataTable

The first step is to extract the currently displayed data from the UI control into a DataTable. This step focuses on capturing visible rows and columns, not on reconstructing the original data source.

Export Displayed Data from DataGridView (WinForms)

In WinForms applications, users typically expect the DataGridView content to be exported as it appears on screen. The following method converts the displayed DataGridView data into a DataTable:

DataTable ConvertDataGridViewToDataTable(DataGridView dgv)
{
    DataTable dt = new DataTable();

    foreach (DataGridViewColumn column in dgv.Columns)
    {
        dt.Columns.Add(column.HeaderText, column.ValueType ?? typeof(string));
    }

    foreach (DataGridViewRow row in dgv.Rows)
    {
        if (row.IsNewRow) continue;

        DataRow dr = dt.NewRow();
        for (int i = 0; i < dgv.Columns.Count; i++)
        {
            dr[i] = row.Cells[i].Value ?? DBNull.Value;
        }
        dt.Rows.Add(dr);
    }

    return dt;
}

This approach preserves column headers, column order, and displayed values when exporting DataGridView data to Excel in C#.

Export Displayed Data from GridView (ASP.NET)

In ASP.NET applications, GridView controls render tabular data for users to view and interact with. To export the displayed GridView data, the rendered rows can be converted into a DataTable as shown below:

DataTable ConvertGridViewToDataTable(GridView gv)
{
    DataTable dt = new DataTable();

    foreach (TableCell cell in gv.HeaderRow.Cells)
    {
        dt.Columns.Add(cell.Text);
    }

    foreach (GridViewRow row in gv.Rows)
    {
        DataRow dr = dt.NewRow();
        for (int i = 0; i < row.Cells.Count; i++)
        {
            dr[i] = row.Cells[i].Text;
        }
        dt.Rows.Add(dr);
    }

    return dt;
}

This method provides a consistent data structure that can be reused for exporting GridView data to Excel in C#, without introducing UI-specific export logic.

If you need to export data directly from a database to an Excel file, you can refer to this guide: Export Database to Excel in C#.


Step 2: Export DataTable to Excel in C#

Once the displayed data has been extracted into a DataTable, exporting it to Excel becomes a UI-independent operation.

In this example, Spire.XLS for .NET is used to generate Excel files programmatically, without requiring Microsoft Excel to be installed.

Install Spire.XLS for .NET

Spire.XLS for .NET can be installed via NuGet:

Install-Package Spire.XLS

You can also download Spire.XLS for .NET and add it to your project manually.

Basic Excel Export Example

using Spire.Xls;

Workbook workbook = new Workbook();
Worksheet worksheet = workbook.Worksheets[0];

// Import DataTable into Excel, including column headers
worksheet.InsertDataTable(exportTable, true, 1, 1);

// Save the Excel file
workbook.SaveToFile("ExportedData.xlsx", ExcelVersion.Version2016);

Below is a preview of the exported Excel file:

Basic DataGridView to Excel Export with C#

This export logic can be reused for DataGrid, DataGridView, and GridView scenarios without modification.


Step 3: Apply Formatting to the Exported Excel File

Formatting is a common requirement for Excel exports, regardless of how the data was sourced. Applying styles, adjusting column widths, and setting number formats significantly improves the usability of the exported file.

The following example demonstrates common formatting operations that can be applied to any exported Excel worksheet:

CellStyle headerStyle = workbook.Styles.Add("HeaderStyle");
headerStyle.Font.IsBold = true;
headerStyle.Font.Size = 13;
headerStyle.HorizontalAlignment = HorizontalAlignType.Center;
headerStyle.VerticalAlignment = VerticalAlignType.Center;
headerStyle.Color = Color.LightGray;

// Apply header style
CellRange headerRange = worksheet.Range[1, 1, 1, worksheet.AllocatedRange.Rows[0].CellsCount];
headerRange.Style = headerStyle;

// Auto-fit columns
worksheet.AllocatedRange.AutoFitColumns();

// Format date and currency columns
worksheet.Range[$"C2:C{worksheet.AllocatedRange.RowCount}"].NumberFormat = "yyyy-mm-dd";
worksheet.Range[$"F2:G{worksheet.AllocatedRange.RowCount}"].NumberFormat = "$#,##0.00";

Below is a preview of the Excel file after applying formatting:

DataGridView to Excel Export with Formatting in C#

These formatting steps can be combined or extended based on reporting requirements, without changing the data extraction logic.

Spire.XLS for .NET also supports more Excel formatting features, such as conditional formatting, charts, and more. You can check How to Create Excel Files in C# for more formating options.


Performance and Practical Considerations

When exporting large DataGrid or GridView datasets:

  • Run export operations asynchronously in desktop applications
  • Avoid blocking the UI thread during Excel generation
  • Export only necessary or visible columns
  • Generate Excel files server-side in ASP.NET applications

Because the export process operates on a DataTable rather than UI elements, it remains maintainable and scalable as data volume increases.


Summary

Exporting DataGrid, DataGridView, or GridView data to Excel in C# does not require Microsoft Office Interop. By extracting the displayed data into a DataTable and generating Excel files programmatically, developers can implement reliable and reusable Excel export functionality.

With consistent formatting support and a clear separation between UI and export logic, this approach works well for real-world reporting scenarios in both desktop and web applications. For evaluating the library or testing export functionality, you can apply for a temporary license.


FAQ

Q1: How can I export DataGridView data to Excel in C#?

A1: You can extract the displayed data from a DataGridView into a DataTable and then use Spire.XLS for .NET to generate an Excel file programmatically, without relying on Microsoft Excel.

Q2: Can I apply formatting when exporting GridView to Excel in C#?

A2: Yes, Spire.XLS allows you to apply styles, adjust column widths, and set number formats to any exported Excel worksheet, ensuring readable and professional-looking reports.

Q3: Do I need Microsoft Excel installed to export DataGrid or GridView data in C#?

A3: No. By using a programmatic library like Spire.XLS, Excel files can be generated directly from DataTable objects without requiring Excel on the machine, making it suitable for server-side and cloud applications.

A guide to create a CSV file using Python

CSV (Comma-Separated Values) files are the backbone of data exchange across industries—from data analysis to backend systems. They’re lightweight, human-readable, and compatible with almost every tool (Excel, Google Sheets, databases). If you’re a developer seeking a reliable way to create a CSV file in Python, Spire.XLS for Python is a powerful library that simplifies the process.

In this comprehensive guide, we'll explore how to generate a CSV file in Python with Spire.XLS, covering basic CSV creation and advanced use cases like list to CSV and Excel to CSV conversion.

What You’ll Learn


Installation and Setup

Getting started with Spire.XLS for Python is straightforward. Follow these steps to set up your environment:

Step 1: Ensure Python 3.6 or higher is installed.

Step 2: Install the library via pip (the official package manager for Python):

pip install Spire.XLS

Step 3 (Optional): Request a temporary free license to test full features without any limitations.


Basic: Create a Simple CSV File in Python

Let’s start with a simple scenario: creating a CSV file from scratch with static data (e.g., a sales report). The code below creates a new workbook, populates it with data, and saves it as a CSV file.

from spire.xls import *
from spire.xls.common import *

# 1. Create a new workbook
workbook = Workbook()
    
# 2. Get the first worksheet (default sheet)
worksheet = workbook.Worksheets[0]

# 3. Populate data into cells
# Header row
worksheet.Range["A1"].Text = "ProductID"
worksheet.Range["B1"].Text = "ProductName"
worksheet.Range["C1"].Text = "Price"
worksheet.Range["D1"].Text = "QuantitySold"

worksheet.Range["A2"].NumberValue = 101
worksheet.Range["B2"].Text = "Wireless Headphones"
worksheet.Range["C2"].NumberValue = 79.99
worksheet.Range["D2"].NumberValue = 250

worksheet.Range["A3"].NumberValue = 102
worksheet.Range["B3"].Text = "Bluetooth Speaker"
worksheet.Range["C3"].NumberValue = 49.99
worksheet.Range["D3"].NumberValue = 180

# Save the worksheet to CSV
worksheet.SaveToFile("BasicSalesReport.csv", ",", Encoding.get_UTF8())
workbook.Dispose()

Core Workflow

  • Initialize Core object: Workbook() creates a new Excel workbook, Worksheets[0] accesses the target sheet.
  • Fill data into cells: Use .Text (for strings) and .NumberValue (for numbers) to ensure correct data types.
  • Export & cleanup: SaveToFile() exports the worksheet to CSV , and Dispose() prevents memory leaks.

Output:

The resulting BasicSalesReport.csv will look like this:

Create a CSV file from scratch using Python


Dynamic Data: Generate CSV from a List of Dictionaries in Python

In real-world scenarios, data is often stored in dictionaries (e.g., from APIs/databases). The code below converts a list of dictionaries to a CSV:

from spire.xls import *
from spire.xls.common import *

# Sample data (e.g., from a database/API)
customer_data = [
    {"CustomerID": 1, "Name": "John Doe", "Email": "john@example.com", "Country": "USA"},
    {"CustomerID": 2, "Name": "Maria Garcia", "Email": "maria@example.es", "Country": "Spain"},
    {"CustomerID": 3, "Name": "Li Wei", "Email": "wei@example.cn", "Country": "China"}
]

# 1. Create workbook and worksheet
workbook = Workbook()
worksheet = workbook.Worksheets[0]

# 2. Write headers (extract keys from the first dictionary)
headers = list(customer_data[0].keys())
for col_idx, header in enumerate(headers, start=1):
    worksheet.Range[1, col_idx].Text = header  # Row 1 = headers

# 3. Write data rows
for row_idx, customer in enumerate(customer_data, start=2):  # Start at row 2
    for col_idx, key in enumerate(headers, start=1):
        # Handle different data types (text/numbers)
        value = customer[key]
        if isinstance(value, (int, float)):
            worksheet.Range[row_idx, col_idx].NumberValue = value
        else:
            worksheet.Range[row_idx, col_idx].Text = value

# 4. Save as CSV
worksheet.SaveToFile("CustomerData.csv", ",", Encoding.get_UTF8())
workbook.Dispose()

This example is ideal for JSON to CSV conversion, database dumps, and REST API data exports. Key advantages include:

  • Dynamic Headers: Automatically extracts headers from the keys of the first dictionary in the dataset.
  • Scalable: Seamlessly adapts to any volume of dictionaries or key-value pairs (perfect for dynamic data).
  • Clean Output: Preserves the original order of dictionary keys for consistent CSV structure.

The generated CSV file:

Convert a list of dictionaries to CSV file using Python


Excel-to-CSV: Generate CSV From an Excel File in Python

Spire.XLS excels at converting Excel (XLS/XLSX) to CSV in Python. This is useful if you have Excel reports and need to export them to CSV for data pipelines or third-party tools.

from spire.xls import *

# 1. Initialize a workbook instance
workbook = Workbook()

# 2. Load a xlsx file
workbook.LoadFromFile("Expenses.xlsx")

# 3. Save Excel as a CSV file
workbook.SaveToFile("XLSXToCSV.csv", FileFormat.CSV)
workbook.Dispose()

Conversion result:

Convert Excel to CSV using Python

Note: By default, SaveToFile() converts only the first worksheet. For converting multiple sheets to separate CSV files, refer to the comprehensive guide: Convert Excel (XLSX/XLS) to CSV in Python – Batch & Multi-Sheet


Best Practices for CSV Creation

Follow these guidelines to ensure robust and professional CSV output:

  1. Validate Data First: Clean empty rows/columns before exporting to CSV.
  2. Use UTF-8 Encoding: Always specify UTF-8 encoding (Encoding.get_UTF8()) to support international characters seamlessly.
  3. Batch Process Smartly: For 100k+ rows, process data in chunks (avoid loading all data into memory at once).
  4. Choose the Correct Delimiter: Be mindful of regional settings. For European users, use a semicolon (;) as the delimiter to avoid locale issues.
  5. Dispose Objects: Release workbook/worksheet resources with Dispose() to prevent memory leaks.

Conclusion

Spire.XLS simplifies the process of leveraging Python to generate CSV files. Whether you're creating reports from scratch, converting Excel workbooks, or handling dynamic data from APIs and databases, this library delivers a robust and flexible solution.

By following this guide, you can easily customize delimiters, specify encodings such as UTF-8, and manage data types—ensuring your CSV files are accurate, compatible, and ready for any application. For more advanced features, you can explore the Spire.XLS for Python tutorials.


FAQ: Create CSV in Python

Q1: Why choose Spire.XLS over Python’s built-in csv module?

A: While Python's csv module is excellent for basic read/write operations, Spire.XLS offers significant advantages:

  • Better data type handling: Automatic distinction between text and numeric data.
  • Excel Compatibility: Seamlessly converts between Excel (XLSX/XLS) and CSV—critical for teams using Excel as a data source.
  • Advanced Customization: Supports customizing the delimiter and encoding of the generated CSV file.
  • Batch processing: Efficient handling of large datasets and multiple files.
  • Cross-Platform Support: Works on Windows, macOS, and Linux (no Excel installation required).

Q2: Can I use Spire.XLS for Python to read CSV files?

A: Yes. Spire.XLS supports parsing CSV files and extracting their data. Details refer to: How to Read CSV Files in Python: A Comprehensive Guide

Q3: Can Spire.XLS convert CSV files back to Excel format?

A: Yes! Spire.XLS supports bidirectional conversion. A quick example:

from spire.xls import *

# Create a workbook
workbook = Workbook()

# Load a CSV file
workbook.LoadFromFile("sample.csv", ",", 1, 1)

# Save CSV as Excel
workbook.SaveToFile("CSVToExcel.xlsx", ExcelVersion.Version2016)

Q4: How do I change the CSV delimiter?

A: The SaveToFile() method’s second parameter controls the delimiter:

# Semicolon (for European locales): 
worksheet.SaveToFile("EU.csv", ";", Encoding.get_UTF8())
# Tab (for tab-separated values/TSV)
worksheet.SaveToFile("TSV_File.csv", "\t", Encoding.get_UTF8())
Page 3 of 333
page 3