
As a .NET developer, you have to deal with DataTable objects very often. Especially, when you need to import or export data from databases or XML/JSON files. While generating documents programmatically, you might need to insert data from the DataTable objects directly into the table in Word documents. For such cases, let me give you the perfect and easiest solution for inserting data from DataTable into a Word document in C#.
- C# Library to Insert DataTable in Word Document
- Steps to Insert DataTable into Word Document
- Insert Data from DataTable into Word DOC
C# Library to Insert DataTable in Word DOC - Free Download
To import data from DataTable objects into Word documents, we will use Aspose.Words for .NET. It is a feature-rich library that lets you create and process MS Word documents. You can either download its DLL or install it from NuGet.
Download DLL
Install via NuGet
PM> Install-Package Aspose.Words
C# Insert DataTable into Word Document - Steps
The following are the steps that we will follow to retrieve data from a DataTable and insert that into the Word document.
- Load data from a database or a data file into the DataTable object.
- Create a new Word document and add a new table to it.
- Loop through the rows in the DataTable and insert each row in Word’s table.
And that’s it.
Let’s now have a look at how to transform these steps into the C# code and import a DataTable into a Word document.
Insert Data from DataTable into Word DOC in C#
First, we will write a method that accepts the DocumentBuilder to build the document, DataTable having data, and an additional parameter to enable/disable importing column headings. Moreover, it returns the Table object.
The following is the workflow of this method.
- Create a new table and get its reference into a Table object.
- Insert columns into the table according to the columns in DataTable.
- Set the font weight if the first row is for headings.
- Loop through each DataRow in DataTable.Rows collection.
- Insert a new cell for each value and set the data type accordingly.
- Return the Table object.
The following is the implementation of the method for importing data from a DataTable into a table in Word document in C#.
/// <summary> | |
/// Imports the content from the specified DataTable into a new Aspose.Words Table object. | |
/// The table is inserted at the current position of the document builder and using the current builder's formatting if any is defined. | |
/// </summary> | |
public static Table ImportTableFromDataTable(DocumentBuilder builder, DataTable dataTable, bool importColumnHeadings) | |
{ | |
Table table = builder.StartTable(); | |
// Check if the names of the columns from the data source are to be included in a header row. | |
if (importColumnHeadings) | |
{ | |
// Store the original values of these properties before changing them. | |
bool boldValue = builder.Font.Bold; | |
ParagraphAlignment paragraphAlignmentValue = builder.ParagraphFormat.Alignment; | |
// Format the heading row with the appropriate properties. | |
builder.Font.Bold = true; | |
builder.ParagraphFormat.Alignment = ParagraphAlignment.Center; | |
// Create a new row and insert the name of each column into the first row of the table. | |
foreach (DataColumn column in dataTable.Columns) | |
{ | |
builder.InsertCell(); | |
builder.Writeln(column.ColumnName); | |
} | |
builder.EndRow(); | |
// Restore the original formatting. | |
builder.Font.Bold = boldValue; | |
builder.ParagraphFormat.Alignment = paragraphAlignmentValue; | |
} | |
foreach (DataRow dataRow in dataTable.Rows) | |
{ | |
foreach (object item in dataRow.ItemArray) | |
{ | |
// Insert a new cell for each object. | |
builder.InsertCell(); | |
switch (item.GetType().Name) | |
{ | |
case "DateTime": | |
// Define a custom format for dates and times. | |
DateTime dateTime = (DateTime)item; | |
builder.Write(dateTime.ToString("MMMM d, yyyy")); | |
break; | |
default: | |
// By default any other item will be inserted as text. | |
builder.Write(item.ToString()); | |
break; | |
} | |
} | |
// After we insert all the data from the current record we can end the table row. | |
builder.EndRow(); | |
} | |
// We have finished inserting all the data from the DataTable, we can end the table. | |
builder.EndTable(); | |
return table; | |
} |
Now, it’s time to call this method and insert a DataTable into a Word document.
Import DataTable into Word Document in C#
The following are the steps to import data from the DataTable into a Word document in C#.
- Create a new Word document (or load an existing one) using Document class.
- Read data from database/file into the DataTable object.
- Call the method that we have written in the previous section and get the returned Table.
- Set formatting of the table.
- Save Word file using Document.Save() method.
The following code sample shows how to insert a DataTable into a Word document in C#.
// Create a new document. | |
Document doc = new Document(); | |
// We can position where we want the table to be inserted and also specify any extra formatting to be | |
// applied onto the table as well. | |
DocumentBuilder builder = new DocumentBuilder(doc); | |
// We want to rotate the page landscape as we expect a wide table. | |
doc.FirstSection.PageSetup.Orientation = Orientation.Landscape; | |
DataSet ds = new DataSet(); | |
ds.ReadXml("Employees.xml"); | |
// Retrieve the data from our data source which is stored as a DataTable. | |
DataTable dataTable = ds.Tables[0]; | |
// Build a table in the document from the data contained in the DataTable. | |
Table table = ImportTableFromDataTable(builder, dataTable, true); | |
// We can apply a table style as a very quick way to apply formatting to the entire table. | |
table.StyleIdentifier = StyleIdentifier.MediumList2Accent1; | |
table.StyleOptions = TableStyleOptions.FirstRow | TableStyleOptions.RowBands | TableStyleOptions.LastColumn; | |
// For our table we want to remove the heading for the image column. | |
table.FirstRow.LastCell.RemoveAllChildren(); | |
// Save the output document. | |
doc.Save("Table.docx"); |
C# DataTable to Word Importer Library - Get a Free License
You can get a free temporary license to use Aspose.Words for .NET without evaluation limitations.
Conclusion
In this article, you have learned how to insert data from a DataTable into a Word document in C#. You can easily integrate the code sample into your applications and import data directly from database/XML/JSON into Word documents using DataTable.
.NET Word Library - Read More
You can visit the documentation of Aspose.Words for .NET to explore more about the library. In case you would have any questions, feel free to let us know via our forum.