【问题标题】:Unable to add new row to exisitng table in word document using WordprocessingDocument无法使用 Word 处理文档向 Word 文档中的现有表添加新行
【发布时间】:2015-05-19 04:53:22
【问题描述】:

我有一个 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 时,我收到以下错误:

我错过了什么?

【问题讨论】:

    标签: c# ms-word openxml


    【解决方案1】:

    我找到了一个快速、轻量级且不需要安装 Microsoft Word 或 Office 的代码 plex 帮助程序 dll。您可以从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");
    }
    

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

    希望这对其他人也有帮助。

    【讨论】:

      【解决方案2】:

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

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

      一个TableRow必须至少包含一个TableCell,一个TableCell必须包含一个Paragraph

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多