0

我有一个动态生成的 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 仅按单词计算。使用互操作是不可能的,因为它太慢了。

4

1 回答 1

0

在 Open XML 中有 2 个选项可以执行此操作。

  1. 从文档末尾的 Microsoft Office 开发人员选项卡创建内容占位符,现在您可以通过编程方式访问此内容占位符,并可以在其中放置任何文本。

  2. 您可以将文本直接附加到您的 word 文档中,并将其插入文本的末尾。在这种方法中,您必须首先将所有内容写入文档,一旦完成,您就可以通过以下方式附加文档

//

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 文档的想法。问候,

于 2013-01-16T12:00:32.987 回答