将DataTable导出到dotx

时间:2015-06-20 23:18:19

标签: c# excel winforms datatable office-interop

我一直在尝试将数据表导出到excel表,但现在我想将数据表导出到word表中。

我有一个单词模板文件,其中包含我希望使用数据表填充该对象的excel嵌入对象。 这里是我用来将自定义值导出到word文件的代码。

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 个答案:

答案 0 :(得分:0)

您可以使用很少的方法来执行此操作。最简单的方法是在word文档中创建一个表并为每个单元格分配字段。但是,通过这种方式,您必须修复表中行数和列数的大小。

您还可以使用另外两种方便的方法。

使用C#.NET

这是从代码动态创建表的最简单方法。但是,一旦应用程序被编译,它就无法直接更改,并且当应用程序在客户端运行时也很难调试。

How to create table programatically

使用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. 记下C#应用程序中的代码,该代码将数据导出为csv格式并存储放置文档的位置。 (How to export datatable into csv file format.

  2. 在文档中创建一个宏,该宏从csv文件中读取数据并创建表。 (Add Table and fill data to the Word document from the csv.

  3. 最后一步是从C#应用程序执行宏。 (How to execute VBA macro by C# code