novacode docx,从datatable创建word表

时间:2018-04-04 14:54:44

标签: c# datatable ms-word novacode-docx

我正在尝试遍历数据表并创建word表。到目前为止,如果我在数据表中有3行,它们将被插入到我的Microsoft Word表的第一行,而我希望数据表中的每一行都进入Microsoft Word表中的新行。 以下是我的代码:

protected void Button2_Click(object sender, EventArgs e)
{
    PullData();
    gvd2.DataSource = dataTable;
    gvd2.DataBind();

    // Create a document.
    using (DocX document = DocX.Create(@"D:\Test.docx"))
    {
        // Add a Table to this document.
        Novacode.Table t = document.AddTable(2, 3);
        // Specify some properties for this Table.
        t.Alignment = Alignment.center;
        t.Design = TableDesign.MediumGrid1Accent2;

        // Add content to this Table.
        t.Rows[0].Cells[0].Paragraphs.First().Append("A");

        //foreach (DataRow row in dataTable.Rows)
        //{
        //    t.Rows[1].Cells[0].Paragraphs.First().Append(row["IssueSubjectType"].ToString());
        //}

        // Loop through the rows in the Table and insert data from the data source.
        for (int row = 1; row < t.RowCount; row++)
        {
            for (int cell = 0; cell < t.Rows[row].Cells.Count; cell++)
            {
                Paragraph cell_paragraph =t.Rows[row].Cells[cell].Paragraphs[0];
                cell_paragraph.InsertText(dataTable.Rows[row - 1].ItemArray[cell].ToString(), false);
            }
        }

        // Insert the Table into the document.
        document.InsertTable(t);
        // Save the Document.
        document.Save();
        // Release this document from memory.
        document.Dispose();
    }
}   


private DataTable dataTable = new DataTable();

//  method to pull data from database to datatable   
public void PullData()
{
    using (SqlConnection sqlConn = new SqlConnection("Data Source=.;Initial Catalog=UAE_OG-Interanl;Integrated Security=True"))
    {
        string sqlQuery = @"SELECT IssueSubjectType from tbl_IssueStoPublicate WHERE IssueNumber = '625'  order by IssueSubjectOrder desc";
        using (SqlCommand cmd = new SqlCommand(sqlQuery, sqlConn))
        {
            SqlDataAdapter ds = new SqlDataAdapter(cmd);
            ds.Fill(dataTable);
        }
    }
}

任何帮助都会成为救星。