2017-03-22 62 views
0

我正在使用OpenXML來操作Microsoft Word文件(.docx)。在Word文檔的開頭插入文本 - openXML

我發送Word文件作爲內存流,編輯它們,然後將它們發送回瀏覽器,以便它們在客戶端辦公程序中打開。

我想插入文本,approximatley 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" }; 

} 

我的問題是,如果我已經從第一行中得到一些文本,那麼我的文本將被追加到原始文本後面。我如何將原始內容向下推,並在上面插入我的文字?

回答

1

使用PrependChild代替Append。追加將始終插入當前元素的末尾。所以如果你已經在第一段中有內容,你的附件會把你的文本放在最後。您也可以通過調用Document.PrependChild(firstParagraph)

+0

將您的文本作爲新的第一段插入。感謝您的提示,Maarten。你知道我怎麼能在我的文字中添加換行/輸入嗎? – Ilyas