无法使用WordprocessingDocument向word文档中的exisitng表添加新行

时间:2015-05-19 04:53:23

标签: c# ms-word openxml

我有一个word文档,其中添加了表格。我想访问该文档并将新的空行添加到其中已有的表中。我提到了this引用链接并在下面创建了代码:

static void Main(string[] args)
{
    string filePath = "C:\\TestDoc1.docx";
    byte[] byteArray = File.ReadAllBytes(filePath);

    using (MemoryStream stream = new MemoryStream())
    {
        stream.Write(byteArray, 0, (int)byteArray.Length);

        using (WordprocessingDocument doc = WordprocessingDocument.Open(stream, true))
        {
            Body bod = doc.MainDocumentPart.Document.Body;
            foreach (Table t in bod.Descendants<Table>().Where(tbl => tbl.GetFirstChild<TableRow>().Descendants<TableCell>().Count() == 4))
            {
                // Create a row.
                TableRow tr = new TableRow();
                t.Append(tr);
            }

        }
        // Save the file with the new name
        File.WriteAllBytes("C:\\TestDoc2.docx", stream.ToArray());
    }
} 

但是,代码不会引发任何错误。但是当我打开TestDoc2.docx时,我收到以下错误:

enter image description here

我错过了什么?

2 个答案:

答案 0 :(得分:0)

我找到了一个快速,轻量级的代码plex helper dll,它不需要安装Microsoft Word或Office。你可以从here获得。将此dll的引用添加到您的解决方案中并写下以下代码:

using(DocX doc = DocX.Load(filePath))
{
    // you can use whatever condition you would like to select the table from that table.
   // I am using the Title field value in the Table Properties wizard under Alter Text tab 
    Novacode.Table t = doc.Tables.Cast<Table>().FirstOrDefault(tbl => tbl.TableCaption == "Test");
    Row r = t.InsertRow();
    doc.SaveAs("C:\\TestDoc2.docx");
}

在我的情况下,它就像一个魅力! : - )

希望这也有助于其他人。

答案 1 :(得分:0)

您的第一个代码中缺少的是TableCell和Paragraph

// Create a row.
TableRow tr = new TableRow(new TableCell(new Paragraph()));
t.Append(tr);

TableRow必须至少包含一个TableCell,而TableCell必须包含段落

相关问题