如何使用openxml添加分节符下一页? [英] How to add section break next page using openxml?

查看:509
本文介绍了如何使用openxml添加分节符下一页?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想在文档末尾添加分节符并添加一些文本.

I want to add a section break at the end of the document and add some text.

我的代码如下:

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();
        }
    }
}

我该怎么办?

推荐答案

您需要将分节符添加到节属性中.然后,您需要将节属性附加到段落属性中.然后将段落属性附加到段落中.

You need to add the section break to the section properties. You then need to append the section properties to the paragraph properties. Followed by appending the paragraph properties to a paragraph.

        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为:

The resulting Open XML is:

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

如果您创建的Word文档看起来像您希望结果显示的样子,请在

If you create a Word document that looks the way you want the result to look, then open in it in the Open XML Productivity Tool, you can reflect the code and see what C# code would generate the various Open XML elements you are trying to achieve.

这篇关于如何使用openxml添加分节符下一页?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆