如何使用wordprocessing document c#在word文档的第15页末尾添加段落

时间:2018-03-27 13:49:48

标签: c# ms-office openxml-sdk

我使用WordprocessingDocument在最后一个段落之后的单词末尾添加段落,但我需要在word文档的第15页末尾添加此段落。

以下是我在文档末尾添加段落的代码:

using (WordprocessingDocument wDoc = WordprocessingDocument.Open(ms, true))
{
    gjenerimi = randomstring(14);
    var body = wDoc.MainDocumentPart.Document.Body;
    var lastParagraf = body.Elements<Paragraph>().LastOrDefault();
    var run = new Run();

    run.AppendChild(new Text(DateTime.Now.ToString() + " , "));
    run.AppendChild(new Text(gjenerimi + " , "));
    run.AppendChild(new Text(merreshifren()));

    lastParagraf.AppendChild(run);
}

1 个答案:

答案 0 :(得分:0)

在评论中,您需要在最后一页添加一个段落,而不是在页面末尾。

要实现此目的,您需要向Paragraph添加新的Body,然后从该Run对象创建Paragraph,然后在Text上附加Run {1}}对象。

示例

Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
Paragraph para = body.AppendChild(new Paragraph());
Run run = para.AppendChild(new Run());
run.AppendChild(new Text("This is my text"));
wordprocessingDocument.Close();
  

更新(根据评论部分中提问者的要求)

如果您想在最后一段之前添加文字,请按照以下步骤操作。

Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
List<Paragraph> paragraphs = body.OfType<Paragraph>()
    .Where(p => p.InnerText != "")
    .ToList();
if(paragraphs.Count > 1)
{
    Paragraph beforeLast = paragraphs[paragraphs.Count - 2];
    Run run = beforeLast.AppendChild(new Run());
    run.AppendChild(new Break()); //Line Break
    run.AppendChild(new Text("This is my text paragraph, before the last one new"));
    run.AppendChild(new Break());
}