OpenXML编辑docx

时间:2013-01-16 08:20:10

标签: openxml docx

我有一个动态生成的docx文件。

需要严格将文字写入页面末尾。

使用Microsoft.Interop我在文本之前插入段落:

int kk = objDoc.ComputeStatistics(WdStatistic.wdStatisticPages, ref wMissing);
while (objDoc.ComputeStatistics(WdStatistic.wdStatisticPages, ref wMissing) != kk + 1)
                {
                    objWord.Selection.TypeParagraph();

                }
                objWord.Selection.TypeBackspace();

但是我不能在Open XML中使用相同的代码,因为pages.count只能用word计算。 使用interop是不可能的,因为它太慢了。

1 个答案:

答案 0 :(得分:0)

在Open XML中有两种选择。

  1. 从文档末尾的Microsoft Office Developer标签创建内容地点持有者,现在您可以以编程方式访问此内容地点持有者,并可在其中放置任何文本。

  2. 您可以将文字干净地附加到您的Word文档中,并将其插入文本末尾。在这种方法中,您必须先将所有内容写入文档,一旦完成,您可以按以下方式附加文档

  3. //

    public void WriteTextToWordDocument()
    {    
        using(WordprocessingDocument doc = WordprocessingDocument.Open(documentPath, true))
        {
            MainDocumentPart mainPart = doc.MainDocumentPart;
            Body body = mainPart.Document.Body;
            Paragraph paragraph = new Paragraph();
            Run run = new Run();
            Text myText = new Text("Append this text at the end of the word document");
            run.Append(myText);
            paragraph.Append(run);
            body.Append(paragraph);
    
            // dont forget to save and close your document as in the following two lines
            mainPart.Document.Save();
            doc.Close();
        }
    }
    

    我没有测试过上面的代码,但希望它会让你知道在OpenXML中处理word文档。 的问候,

相关问题