c# – 如何使用openxml添加分节符下一页?

前端之家收集整理的这篇文章主要介绍了c# – 如何使用openxml添加分节符下一页?前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我想在文档的末尾添加一个分节符并添加一些文本.

我的代码如下:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;

namespace WordDocManipulation
{
    class Program
    {
        static void Main(string[] args)
        {

            string path = @"C:\sample.docx";
            string strtxt = "Hello This is done by programmatically";      

           OpenAndAddTextToWordDocument(path,strtxt);
        }
        public static void OpenAndAddTextToWordDocument(string filepath,string txt)
        {
            /* I want to the below text to be added in the new section */ 

            // Open a WordprocessingDocument for editing using the filepath.
            WordprocessingDocument wordprocessingDocument =
                WordprocessingDocument.Open(filepath,true);

            // Assign a reference to the existing document body.
            Body body = wordprocessingDocument.MainDocumentPart.Document.Body;

            // Add new text.
            Paragraph para = body.AppendChild(new Paragraph());
            Run run = para.AppendChild(new Run());
            run.AppendChild(new Text(txt));

            // Close the handle explicitly.
            wordprocessingDocument.Close();
        }
    }
}

我该怎么办?

解决方法

您需要将分节符添加到节属性中.然后,您需要将section属性附加到段落属性.然后将段落属性附加到段落.
Paragraph paragraph232 = new Paragraph();

        ParagraPHProperties paragraPHProperties220 = new ParagraPHProperties();

        SectionProperties sectionProperties1 = new SectionProperties();
        SectionType sectionType1 = new SectionType(){ Val = SectionMarkValues.NextPage };

        sectionProperties1.Append(sectionType1);

        paragraPHProperties220.Append(sectionProperties1);

        paragraph232.Append(paragraPHProperties220);

生成的Open XML是:

<w:p>
    <w:pPr>
      <w:sectPr>
        <w:type w:val="nextPage" />
      </w:sectPr>
    </w:pPr>
  </w:p>

如果您创建一个看起来像希望结果的Word文档,然后在Open XML Productivity Tool中打开它,您可以反映代码并查看C#代码生成您尝试实现的各种Open XML元素.

原文链接:https://www.f2er.com/csharp/244085.html

猜你在找的C#相关文章