In modern C# application development, exporting program data into a structured and user-friendly Word document is a very common requirement. Whether you are generating reports, contracts, or other business documents, manually creating Word files is not only time-consuming but also error-prone. This problem becomes even more apparent when dealing with large datasets or scenarios that require frequent document generation.
This article provides an efficient and automated solution using Spire.Doc for .NET, enabling C# developers to easily export data from a DataTable into a Word document and present it clearly in table form. Through detailed steps and complete code examples, you will be able to apply this technique smoothly in your own projects.
Why Choose Spire.Doc for .NET?
Spire.Doc for .NET is a powerful and easy-to-integrate .NET component specifically designed for Word document processing. It allows developers to create, read, edit, convert, and print Word documents without relying on Microsoft Office.
When exporting DataTable data to Word documents, Spire.Doc for .NET offers several key advantages:
-
Comprehensive table support: Easily create tables, set table styles (borders, background colors, alignment), and merge cells—perfectly matching the two-dimensional structure of a
DataTable. - Rich formatting options: Fine-grained control over text, paragraphs, images, and other elements, making it easy to produce professional-looking documents.
- High performance and stability: Suitable for large datasets and complex documents while maintaining reliable performance.
- Easy integration and developer-friendly API: Can be added via NuGet and programmed through intuitive, well-designed APIs.
Environment Setup and Library Installation
Before using Spire.Doc for .NET, you need to add it to your C# project.
Create or open a .NET project
Make sure you have a Visual Studio project (Console App, WinForms, WPF, or ASP.NET).Install the NuGet package
In Visual Studio, right-click your project and select Manage NuGet Packages…
- Under the Browse tab, search for
Spire.Doc - Locate the
Spire.Docpackage and click Install
Alternatively, open the Package Manager Console and run:
Install-Package Spire.Doc
After installation, your project will reference the Spire.Doc for .NET library and you can start coding.
Core Implementation: Exporting a DataTable to a Word Table
Next, let’s walk through the process of exporting a DataTable into a table inside a Word document.
Step Breakdown
-
Create the Word document object: Initialize
DocumentandSectionas the basic structure. -
Prepare the DataTable: Create a sample
DataTablefor demonstration purposes. In real scenarios, data usually comes from databases or APIs. -
Create a Word table: Add a
Tableobject to the section. - Apply table styles: Set borders, background colors, row height, column width, and text alignment.
-
Populate the header row: Use the
Columnscollection of theDataTableas table headers. -
Populate data rows: Loop through the
Rowscollection and fill table cells. - Save the document: Export the Word file to a specified path.
Code Example
Below is the complete C# example demonstrating how to export a simulated DataTable to a Word document:
using System;
using System.Data;
using Spire.Doc;
using Spire.Doc.Documents;
using Spire.Doc.Fields;
using System.Drawing;
public class DataTableToWordExporter
{
public static void ExportDataTableToWord(DataTable dataTable, string filePath)
{
// 1. Create a Word document
Document document = new Document();
Section section = document.AddSection();
// Add a title paragraph
Paragraph titleParagraph = section.AddParagraph();
titleParagraph.Format.HorizontalAlignment = HorizontalAlignment.Center;
TextRange titleText = titleParagraph.AppendText("Product Sales Report");
titleText.CharacterFormat.FontSize = 20;
titleText.CharacterFormat.Bold = true;
section.AddParagraph().AppendText(Environment.NewLine); // Blank line
// 2. Prepare DataTable data
// (The DataTable is assumed to be provided by the caller)
// Check whether the DataTable contains data
if (dataTable == null || dataTable.Rows.Count == 0)
{
Paragraph noDataParagraph = section.AddParagraph();
noDataParagraph.AppendText("No data is available for export.");
document.SaveToFile(filePath, FileFormat.Docx);
Console.WriteLine("No data found. The document has been saved.");
return;
}
// 3. Create a Word table
Table table = section.AddTable(true);
table.ResetCells(dataTable.Rows.Count + 1, dataTable.Columns.Count); // +1 for header row
// 4. Set table styles
table.TableFormat.Borders.LineWidth = 1;
table.TableFormat.Borders.BorderType = BorderStyle.Single;
table.TableFormat.Borders.Color = Color.Black;
table.PreferredWidth = new PreferredWidth(WidthType.Percentage, 100);
table.TableFormat.HorizontalAlignment = RowAlignment.Center;
// 5. Populate the header row
TableRow headerRow = table.Rows[0];
headerRow.IsHeader = true;
headerRow.RowFormat.BackColor = Color.LightGray;
headerRow.RowFormat.Height = 25;
headerRow.RowFormat.HeightType = TableRowHeightType.Exactly;
for (int i = 0; i < dataTable.Columns.Count; i++)
{
headerRow.Cells[i].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
Paragraph p = headerRow.Cells[i].AddParagraph();
p.Format.HorizontalAlignment = HorizontalAlignment.Center;
TextRange tr = p.AppendText(dataTable.Columns[i].ColumnName);
tr.CharacterFormat.Bold = true;
tr.CharacterFormat.FontSize = 11;
}
// 6. Populate data rows
for (int r = 0; r < dataTable.Rows.Count; r++)
{
TableRow dataRow = table.Rows[r + 1];
dataRow.RowFormat.Height = 20;
dataRow.RowFormat.HeightType = TableRowHeightType.Exactly;
for (int c = 0; c < dataTable.Columns.Count; c++)
{
dataRow.Cells[c].CellFormat.VerticalAlignment = VerticalAlignment.Middle;
Paragraph p = dataRow.Cells[c].AddParagraph();
p.Format.HorizontalAlignment = HorizontalAlignment.Center;
TextRange tr = p.AppendText(dataTable.Rows[r][c].ToString());
tr.CharacterFormat.FontSize = 10;
}
}
// 7. Save the document
try
{
document.SaveToFile(filePath, FileFormat.Docx);
Console.WriteLine($"The DataTable has been successfully exported to: {filePath}");
}
catch (Exception ex)
{
Console.WriteLine($"An error occurred while exporting the Word document: {ex.Message}");
}
}
public static void Main(string[] args)
{
// Create a sample DataTable
DataTable dt = new DataTable("Products");
dt.Columns.Add("Product ID", typeof(int));
dt.Columns.Add("Product Name", typeof(string));
dt.Columns.Add("Unit Price", typeof(decimal));
dt.Columns.Add("Stock Quantity", typeof(int));
dt.Columns.Add("Release Date", typeof(DateTime));
dt.Rows.Add(101, "Laptop", 8999.00m, 50, new DateTime(2023, 1, 15));
dt.Rows.Add(102, "Smartphone", 4599.00m, 120, new DateTime(2023, 3, 10));
dt.Rows.Add(103, "Wireless Earbuds", 799.00m, 200, new DateTime(2023, 2, 20));
dt.Rows.Add(104, "Smartwatch", 1299.00m, 80, new DateTime(2023, 4, 5));
dt.Rows.Add(105, "Portable Speaker", 399.00m, 150, new DateTime(2023, 5, 1));
string outputPath = "ProductReport.docx";
ExportDataTableToWord(dt, outputPath);
// Demonstrate the empty DataTable scenario
DataTable emptyDt = new DataTable("Empty");
emptyDt.Columns.Add("ID");
string emptyOutputPath = "EmptyReport.docx";
ExportDataTableToWord(emptyDt, emptyOutputPath);
}
}
Result Preview
Below is a preview of the Word document generated by the code above:
Key API Methods Summary
| Method / Property | Description |
|---|---|
Document document = new Document(); |
Creates a new Word document object. |
Section section = document.AddSection(); |
Adds a section to the document; Word content is typically placed in sections. |
Table table = section.AddTable(true); |
Adds a table to the section; true indicates the table auto-fits its content. |
table.ResetCells(rows, columns); |
Initializes the number of rows and columns in the table. |
table.TableFormat.Borders.* |
Sets the table border style, width, and color. |
table.PreferredWidth |
Sets the preferred table width, either by percentage or fixed value. |
TableRow row = table.Rows[index]; |
Gets a specific row from the table. |
row.IsHeader = true; |
Marks the specified row as a header row. |
row.RowFormat.BackColor |
Sets the background color of the row. |
row.RowFormat.Height |
Sets the row height. |
TableCell cell = row.Cells[index]; |
Gets a specific cell from the row. |
cell.CellFormat.VerticalAlignment |
Sets the vertical alignment of the cell content. |
Paragraph p = cell.AddParagraph(); |
Adds a paragraph to the cell to host text content. |
p.Format.HorizontalAlignment |
Sets the horizontal alignment of the paragraph text. |
TextRange tr = p.AppendText(text); |
Appends text to the paragraph. |
tr.CharacterFormat.* |
Sets text formatting such as font, size, color, and bold style. |
document.SaveToFile(filePath, FileFormat.Docx); |
Saves the document to the specified path and supports multiple file formats. |
Advanced Tips and Best Practices
Style Customization
The code above demonstrates only basic styling. Spire.Doc for .NET provides a rich set of APIs that allow you to apply more advanced and fine-grained formatting to Word documents:
-
Fonts and colors: Use the
CharacterFormatobject to configure font family, size, color, italics, underline, and more. -
Paragraph formatting:
ParagraphFormatcontrols indentation, line spacing, alignment, and paragraph spacing. - Conditional formatting: Apply background colors or text colors to cells based on data values (for example, highlighting low inventory levels).
-
Headers and footers: Use
section.HeadersFooters.Headerandsection.HeadersFooters.Footerto add headers and footers with page numbers, dates, or other metadata.
Handling Complex Data Types
When a DataTable contains dates, Boolean values, or custom objects, additional formatting may be required during export:
-
Date formatting: Use methods such as
DateTime.ToString("yyyy-MM-dd")to display dates in a user-friendly format. -
Boolean values: Convert
trueandfalseinto readable text such as “Yes” and “No”. -
Custom objects: For columns containing custom objects, override the
ToString()method or apply business-specific formatting logic to ensure meaningful output in the Word document.
// Example: Date formatting
if (dataTable.Columns[c].DataType == typeof(DateTime))
{
DateTime dateValue = (DateTime)dataTable.Rows[r][c];
p.AppendText(dateValue.ToString("yyyy-MM-dd"));
}
else
{
p.AppendText(dataTable.Rows[r][c].ToString());
}
Error Handling
In production environments, it is essential to implement robust error-handling mechanisms. Using try-catch blocks helps capture issues such as file save failures or data conversion errors, improving application stability.
try
{
// ... Word document generation logic ...
document.SaveToFile(filePath, FileFormat.Docx);
}
catch (Exception ex)
{
// Log the error or display a user-friendly message
Console.Error.WriteLine($"An error occurred while exporting the Word document: {ex.Message}");
// Additional recovery logic can be implemented here if needed
}
Performance Considerations
When working with DataTable objects containing thousands or even tens of thousands of rows, generating a Word document in a single operation may consume significant memory and processing time. Consider the following optimization strategies:
- Batch processing: If the document structure allows, split large datasets into smaller batches, generate document sections separately, and merge them afterward.
- Streaming approaches: Although Spire.Doc primarily uses a DOM (Document Object Model) approach, for extremely large datasets you may explore lower-level streaming techniques—keeping in mind that this increases implementation complexity.
-
Optimize the data source: Ensure that the
DataTablepassed into the export method is already optimized and contains only the data required for the document.
Summary
This article demonstrated how to efficiently and automatically export data from a DataTable to a structured Word document using C# and Spire.Doc for .NET. From environment setup and core implementation to advanced tips and performance considerations, we covered a complete and practical solution.
With Spire.Doc for .NET, developers can not only handle common Word export scenarios with ease, but also leverage its rich APIs to apply advanced formatting and handle complex data types—significantly improving both development efficiency and document quality. We encourage you to further explore the powerful features of Spire.Doc for .NET and unlock more possibilities for document processing in your C# applications.


Top comments (0)