【问题标题】:OpenXML editing docxOpenXML 编辑文档
【发布时间】:2013-01-16 08:20:09
【问题描述】:

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

【问题讨论】:

    标签: openxml docx


    【解决方案1】:

    在 Open XML 中有两种选择。

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

    【讨论】:

    • 你不懂我。我有任何内容的内容控件,需要将其移至页面末尾)在编辑之前我无法将其移至末尾
    • 由于我很困惑,但仍然不清楚,能否请您再解释一下您的情况?
    猜你喜欢
    • 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
    相关资源
    最近更新 更多