在 Word 文档的开头插入文本 - openXML

问题描述 投票:0回答:1

我正在使用 OpenXML 来操作 Microsoft Word 文件 (.docx)。

我将 Word 文件作为内存流发送,编辑它们,然后将它们发送回浏览器,以便它们在客户端办公程序中打开。

我想在已经有内容的文档开头插入大约 10 行文本。我就是这样做的;

using (var wordprocessingDocument = WordprocessingDocument.Open(mem, true))
{   
    Paragraph firstParagraph = wordprocessingDocument.MainDocumentPart.Document.Descendants<Paragraph>().First();   


    Run run1 = new Run();
    Text text1 = new Text();
    text1.Text = "Document type: ";

    run1.Append(text1);

    Run run2 = new Run();
    Break break1 = new Break();

    run2.Append(break1);
    ProofError proofError1 = new ProofError() { Type = ProofingErrorValues.SpellStart };

    Run run3 = new Run();
    Text text2 = new Text();
    text2.Text = "Document ID";

    run3.Append(text2);
    ProofError proofError2 = new ProofError() { Type = ProofingErrorValues.SpellEnd };

    Run run4 = new Run();
    Break break2 = new Break();
    Text text3 = new Text();
    text3.Text = "Document Title";

    run4.Append(break2);
    run4.Append(text3);

    firstParagraph.Append(run1);
    firstParagraph.Append(run2);
    firstParagraph.Append(proofError1);
    firstParagraph.Append(run3);
    firstParagraph.Append(proofError2);
    firstParagraph.Append(run4);

    Paragraph paragraph3 = new Paragraph() { RsidParagraphAddition = "0068718C", RsidParagraphProperties = "0068718C", RsidRunAdditionDefault = "00E1050C" };

    Run run5 = new Run();
    Text text4 = new Text();
    text4.Text = "A";

    run5.Append(text4);

    Run run6 = new Run() { RsidRunAddition = "00126F2D" };
    Text text5 = new Text();
    text5.Text = "tlet";

    run6.Append(text5);

    paragraph3.Append(run5);
    paragraph3.Append(run6);

    Paragraph paragraph4 = new Paragraph() { RsidParagraphMarkRevision = "0068718C", RsidParagraphAddition = "00E1050C", RsidParagraphProperties = "0068718C", RsidRunAdditionDefault = "00E1050C" };
    BookmarkStart bookmarkStart1 = new BookmarkStart() { Name = "_GoBack", Id = "0" };
    BookmarkEnd bookmarkEnd1 = new BookmarkEnd() { Id = "0" };

    paragraph4.Append(bookmarkStart1);
    paragraph4.Append(bookmarkEnd1);

    SectionProperties sectionProperties1 = new SectionProperties() { RsidRPr = "0068718C", RsidR = "00E1050C", RsidSect = "000C7A63" };

}

我的问题是,如果我已经从第一行获得了一些文本,那么我的文本将附加在原始文本之后。如何将原始内容向下推几行,并在上面插入我的文字?

c# sharepoint ms-word openxml openxml-sdk
1个回答
3
投票

使用

PrependChild<T>
而不是
Append
Append
将始终插入到当前元素的末尾。因此,如果第一段中已有内容,则追加会将文本放在末尾。您还可以通过调用
Document.PrependChild<Paragraph>(firstParagraph)

将文本插入为新的第一段
© www.soinside.com 2019 - 2024. All rights reserved.