Exporting DataTable to MS word table in dotx

2.4k Views Asked by At

I have been trying to export datatable to excel sheet but now i want to export datatable into word table.

i have a word template file which contains the excel embedded object i want to populate that object using datatable. here to the code i have been using to export custom values to word file.

Object oMissing = System.Reflection.Missing.Value;
Object oTemplatePath = "D:\\Mujahid.dotx";

Application wordApp = new Application();
Document wordDoc = new Document();
wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);

foreach (Field myMergeField in wordDoc.Fields)
{
    Range rngFieldCode = myMergeField.Code;
    String fieldText = rngFieldCode.Text;

    // ONLY GETTING THE MAILMERGE FIELDS
    if (fieldText.StartsWith(" MERGEFIELD"))
    {
        // THE TEXT COMES IN THE FORMAT OF
        // MERGEFIELD  MyFieldName  \\* MERGEFORMAT
        // THIS HAS TO BE EDITED TO GET ONLY THE FIELDNAME "MyFieldName"
        Int32 endMerge = fieldText.IndexOf("\\");
        Int32 fieldNameLength = fieldText.Length - endMerge;
        String fieldName = fieldText.Substring(11, endMerge - 11);

        // GIVES THE FIELDNAMES AS THE USER HAD ENTERED IN .dot FILE
        fieldName = fieldName.Trim();

        // **** FIELD REPLACEMENT IMPLEMENTATION GOES HERE ****//
        // THE PROGRAMMER CAN HAVE HIS OWN IMPLEMENTATIONS HERE
        if (fieldName == "SaleID")
        {
            myMergeField.Select();
            wordApp.Selection.TypeText("12345667890");
        }
        else if (fieldName == "date")
        {
            myMergeField.Select();
            wordApp.Selection.TypeText(DateTime.Today.ToShortDateString());
        }
        else if (fieldName == "CustName")
        {
            myMergeField.Select();
            wordApp.Selection.TypeText("Mujahid Niaz");
        }
        else if (fieldName == "CustAddress")
        {
            myMergeField.Select();
            wordApp.Selection.TypeText("House No 113 Street 8B Bilal Colony Shamasabad Rawalpindi");
        }
        else if (fieldName == "CustContact")
        {
            myMergeField.Select();
            wordApp.Selection.TypeText("03137203842");
        }
    }
}
SqlConnection conn= new SqlConnection(@"Data Source=(localdb)\Projects;Initial Catalog=SpareParts;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=False");
conn.Open();
SqlDataAdapter adp = new SqlDataAdapter("Select* from Items", conn);
DataSet ds = new DataSet();
adp.Fill(ds);
CreateWordTableWithDataTable(ds.Tables[0]);
wordDoc.Merge("D:\\M.xlsx");
wordDoc.SaveAs("myfile.doc");
wordApp.Documents.Open("myFile.doc");
1

There are 1 best solutions below

0
On

There are few method that you can use to do this. The simplest way is that create a table in word document and assign field to each cell. But, in this way you have to fix the size of number of rows and column in your table.

There are also another two handy methods that you can use it.

using C#.NET

Its a simplest way to create table dynamically from the code. But, once the application is compiled it cannot be changed directly and also it is difficult to debug when the application is running at client side.

How to create table programatically

using VBA

  This method is little bit hard and complex but, once you done it you can easily manage the document at client side without re-compiling your C# application. 

  1. Write down the code in you C# application that exports the data into csv format and stores at where the document is placed. (How to export datatable into csv file format.)

  2. Create a macro in your document that reads the data from the csv file and creates a table. (Add Table and fill data to the Word document from the csv.)

  3. The last step is executing macro from the C# application. (How to execute VBA macro by C# code)