This article explains about how to create a MS Word Document and insert a table in it through visual C# code.
In the example given, I have a data table with a set of values. My aim is to display these values in a tabular form in Microsoft Office Word.
For working with Microsoft office word in C#, we have to add reference to Microsoft Object Library from our solution.
Right Click on the project->Add Reference->COM->Microsoft Object Library.
Once this is done, we can see Microsoft.Office.Interop.Word in the Solution Explorer under References. To use this in code, we have to use the following Namespace.
using Microsoft.Office.Interop.Word;
As said earlier, in data table, I have some set of values. These values has to be inserted into a table. For that first we have to create the Microsoft Word Document.
For creating the table in the document we can use the function Tables.Add() which requires 4 parameters. WordRange implies the range of the document, which is given as till end of the document in normal scenarios.
Another important function to be noted is Table.Borders.Enable, for setting the border for table.
Keep in mind that for word table the index starts from [1,1] in spite of how it is in for datatable [0,0]
protected void btnExport_Click(object sender, EventArgs e)
{
System.Data.DataTable dt = createDataTable();
int iRowCount = dt.Rows.Count;
int iColCount = dt.Columns.Count;
object objMissing = System.Reflection.Missing.Value;
object objEndOfDoc = "\\endofdoc";
Document Wdc = new Document();
Range WordRange = Wdc.Bookmarks.get_Item(ref objEndOfDoc).Range;
Microsoft.Office.Interop.Word.Table wordTable;
wordTable = Wdc.Tables.Add(WordRange,iRowCount, iColCount, ref objMissing, ref objMissing);
int iTableRow = 1;
int iTableCol = 1;
for (int i = 0; i < dt.Columns.Count; i++)
{
wordTable.Cell(iTableRow, iTableCol).Range.Text = dt.Columns[i].ColumnName;
iTableCol++;
}
iTableRow++;
for (int i = 0; i < dt.Rows.Count; i++)
{
iTableCol = 1;
for (int j = 0; j < dt.Columns.Count; j++)
{
wordTable.Cell(iTableRow, iTableCol).Range.Text = dt.Rows[i][j].ToString();
Response.Write(dt.Rows[i][j].ToString());
iTableCol++;
}
iTableRow++;
}
wordTable.Borders.Enable = 1;
Wdc.SaveAs("E:\\test.docx");
}