加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

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

发布时间:2020-12-15 08:34:44 所属栏目:百科 来源:网络整理
导读:我想在文档的末尾添加一个分节符并添加一些文本. 我的代码如下: using System;using System.Collections.Generic;using System.Linq;using System.Text;using DocumentFormat.OpenXml.Packaging;using DocumentFormat.OpenXml.Wordprocessing;namespace Wor
我想在文档的末尾添加一个分节符并添加一些文本.

我的代码如下:

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元素.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读