OpenXml SDK 2.0 创建Word文档 添加页、段落、页眉和页脚

时间:2022-09-25 17:25:51
            using (WordprocessingDocument objWordDocument = WordprocessingDocument.Create(@"C:\********.docx", WordprocessingDocumentType.Document))
{
MainDocumentPart objMainDocumentPart = objWordDocument.AddMainDocumentPart();
Document objDocument = new Document();
Body objBody = new Body();
objDocument.Append(objBody);
objMainDocumentPart.Document = objDocument;
}

转自 http://blog.csdn.net/songpengpeng20100202/article/details/7071030

1. 创建word文档作为模版

2. 以下代码实现需求

using DocumentFormat.OpenXml.Packaging;
using System.IO;
using DocumentFormat.OpenXml.Wordprocessing; namespace OpenXmlAddParagraphsToNewPage
{
class Program
{
static void Main(string[] args)
{
if (File.Exists("copy.docx"))
{
File.Delete("copy.docx");
} File.Copy("InsertNewPageAndParagraphs.docx", "copy.docx");
using (WordprocessingDocument doc = WordprocessingDocument.Open("copy.docx", true))
{
var body = doc.MainDocumentPart.Document.Body; Paragraph newPara = new Paragraph(new Run
(new Break() { Type = BreakValues.Page },
new Text("text on the new page"))); body.Append(newPara); AddHeader(doc);
AddFooter(doc);
doc.MainDocumentPart.Document.Save();
}
} private static void AddFooter(WordprocessingDocument doc)
{
// Declare a string for the header text.
string newFooterText =
"New footer via Open XML Format SDK 2.0 classes"; // Get the main document part.
MainDocumentPart mainDocPart = doc.MainDocumentPart; // Delete the existing footer parts.
mainDocPart.DeleteParts(mainDocPart.FooterParts); // Create a new footer part and get its relationship id.
FooterPart newFooterPart = mainDocPart.AddNewPart<FooterPart>();
string rId = mainDocPart.GetIdOfPart(newFooterPart); // Call the GeneratePageFooterPart helper method, passing in
// the footer text, to create the footer markup and then save
// that markup to the footer part.
GeneratePageFooterPart(newFooterText).Save(newFooterPart); // Loop through all section properties in the document
// which is where footer references are defined.
foreach (SectionProperties sectProperties in
mainDocPart.Document.Descendants<SectionProperties>())
{
// Delete any existing references to footers.
foreach (FooterReference footerReference in
sectProperties.Descendants<FooterReference>())
sectProperties.RemoveChild(footerReference); // Create a new footer reference that points to the new
// footer part and add it to the section properties.
FooterReference newFooterReference =
new FooterReference() { Id = rId, Type = HeaderFooterValues.Default };
sectProperties.Append(newFooterReference);
} // Save the changes to the main document part.
mainDocPart.Document.Save();
} private static void AddHeader(WordprocessingDocument doc)
{
// Declare a string for the header text.
string newHeaderText =
"New header via Open XML Format SDK 2.0 classes"; // Get the main document part.
MainDocumentPart mainDocPart = doc.MainDocumentPart; // Delete the existing header parts.
mainDocPart.DeleteParts(mainDocPart.HeaderParts); // Create a new header part and get its relationship id.
HeaderPart newHeaderPart = mainDocPart.AddNewPart<HeaderPart>();
string rId = mainDocPart.GetIdOfPart(newHeaderPart); // Call the GeneratePageHeaderPart helper method, passing in
// the header text, to create the header markup and then save
// that markup to the header part.
GeneratePageHeaderPart(newHeaderText).Save(newHeaderPart); // Loop through all section properties in the document
// which is where header references are defined.
foreach (SectionProperties sectProperties in
mainDocPart.Document.Descendants<SectionProperties>())
{
// Delete any existing references to headers.
foreach (HeaderReference headerReference in
sectProperties.Descendants<HeaderReference>())
sectProperties.RemoveChild(headerReference); // Create a new header reference that points to the new
// header part and add it to the section properties.
HeaderReference newHeaderReference =
new HeaderReference() { Id = rId, Type = HeaderFooterValues.Default };
sectProperties.Append(newHeaderReference);
} // Save the changes to the main document part.
//mainDocPart.Document.Save(); } // Creates an header instance and adds its children.
private static Header GeneratePageHeaderPart(string HeaderText)
{
// set the position to be the center
PositionalTab pTab = new PositionalTab()
{
Alignment = AbsolutePositionTabAlignmentValues.Center,
RelativeTo = AbsolutePositionTabPositioningBaseValues.Margin,
Leader = AbsolutePositionTabLeaderCharValues.None
}; var element =
new Header(
new Paragraph(
new ParagraphProperties(
new ParagraphStyleId() { Val = "Header" }),
new Run(pTab,
new Text(HeaderText))
)
); return element;
} // Creates an Footer instance and adds its children.
private static Footer GeneratePageFooterPart(string FooterText)
{
PositionalTab pTab = new PositionalTab()
{
Alignment = AbsolutePositionTabAlignmentValues.Center,
RelativeTo = AbsolutePositionTabPositioningBaseValues.Margin,
Leader = AbsolutePositionTabLeaderCharValues.None
}; var elment =
new Footer(
new Paragraph(
new ParagraphProperties(
new ParagraphStyleId() { Val = "Footer" }),
new Run(pTab,
new Text(FooterText))
)
);
return elment;
}
}
}

3. 运行效果

OpenXml SDK 2.0 创建Word文档  添加页、段落、页眉和页脚

转自 http://blog.csdn.net/songpengpeng20100202/article/details/7071030

OpenXml SDK 2.0 创建Word文档 添加页、段落、页眉和页脚的更多相关文章

  1. C&num;实现通过模板自动创建Word文档的方法

    原文地址:http://www.jb51.net/article/55332.htm   本文实例讲述了C#实现通过模板自动创建Word文档的方法,是非常实用的技巧.分享给大家供大家参考.具体实现方法 ...

  2. 在C&num;中创建word文档

    在下面文档中  首先引用word组件:Microsoft.Office.Interop.Word 在头文件中写上 using Word = Microsoft.Office.Interop.Word; ...

  3. Java 后台创建word 文档

    ---恢复内容开始--- Java 后台创建 word 文档 自己总结  网上查阅的文档 分享POI 教程地址:http://www.tuicool.com/articles/emqaEf6 方式一. ...

  4. &lbrack;java&comma;2017-05-04&rsqb; 创建word文档

    package test; import java.text.SimpleDateFormat; import java.util.Date; import com.aspose.words.Data ...

  5. Python批量创建word文档(2)- 加图片和表格

    Python创建word文档,任务要求:小杨在一家公司上班,每天都需要给不同的客户发送word文档,以告知客户每日黄金价格.要求在文档开始处给出banner条,价格日期等用表格表示.最后贴上自己的联系 ...

  6. OpenXml入门----给Word文档添加文字

    使用OpenXml给word文档添加文字,每个模块都有自己对于的属性以及内容,要设置样式就先声明属性对象,将样式Append到属性里面,再将属性append到模块里面,那么模块里面的内容就具备该样式了 ...

  7. Python批量创建word文档(1)- 纯文字

    Python创建word文档,任务要求:小杨在一家公司上班,每天都需要给不同的客户发送word文档,以告知客户每日黄金价格.最后贴上自己的联系方式.代码如下: 1 ''' 2 #python根据需求新 ...

  8. 向Docx4j生成的word文档添加图片和布局--第一部分

    原文标题:Adding images and layout to your Docx4j-generated word documents, part 1 原文链接:http://blog.iprof ...

  9. Java 如何给Word文档添加多行文字水印

    前言 我在以往的文章中曾介绍过如何给Word文档添加文本水印和图片水印,及怎样删除文档中的水印.关于文本水印,之前那篇教程里主要指的是单行字体的水印,而在操作Word文档时,有时也会碰到需要添加多行文 ...

随机推荐

  1. OD调试17

    程序先出现一个nag 然后出现主窗口 然后出现第二个nag窗口        我们查个壳   没有壳 那就载入OD看看,继续用调用堆栈的方法 发现一直执行用的都是这一个call,最后执行到程序结束.之 ...

  2. &lbrack;js开源组件开发&rsqb;数字或金额千分位格式化组件

    数字或金额千分位格式化组件 这次距离上一个组件<[js开源组件开发]table表格组件>时隔了一个月,由于最近的项目比较坑,刚挖完坑,所以来总结性提出来几个组件弥补这次的空缺,首先是金额和 ...

  3. SFTP和FTS协议的区别

    都是为FTP连接加密,协议非常相似.一个是借助SSL协议加密,一个时借助SSH协议加密.SSL是为HTTP/SMTP等加密设计的:SSH是为TELNET/FTP等加密.建立传输通道而设计的.其实SSH ...

  4. MySQL 5&period;5&period;35 单机多实例配置详解

    一.前言 二.概述 三.环境准备 四.安装MySQL 5.5.35 五.新建支持多实例的配置文件(我这里配置的是四个实例) 六.初始化多实例数据库 七.提供管理脚本 mysqld_multi.serv ...

  5. HTML对JSON的操作

    <html> <head> <meta http-equiv="Content-Type" content="text/html; char ...

  6. win10 UWP 蜘蛛网效果

    我看见了知乎首页登录背景和普通的地球人写的博客,发现了个好看的效果. 那么我来告诉大家如何做这个效果. 第一步是在 Canvas 画点,第二步是让点移动,第三步是画线 在 Canvas 画一个点 我们 ...

  7. HDU 4923 Room and Moor (多校第六场C题) 单调栈

    Problem Description PM Room defines a sequence A = {A1, A2,..., AN}, each of which is either 0 or 1. ...

  8. Asp&period;Net SignalR Hub集线器

    集线器Hub类 使用持久连接类去开发是有些困难的,因为基于事件的开发方式,我们可以进行操作的地方也仅仅只是OnReceived事件内,这有些像websocket的方式.我们迫切的需要一种更人性化,更为 ...

  9. SPRING 事务管理说明

    spring 事务管理是通过AOP拦截指定的方法,进行事务管理. 事务配置 <aop:config proxy-target-class="true"> <aop ...

  10. 远程桌面如何向远程的计算机发送ctrl&plus;alt&plus;del

    远程桌面如何向远程的计算机发送ctrl+alt+del ? 可以使用 ctrl+alt+end 组合键代替 ctrl+alt+del 组合键