一:OpenXml Sdk 简介

  Open XML标准的简单介绍:Ecma Office Open XML(“Open XML”)是针对字处理文档、演示文稿电子表格的国际化开放标准,可免费供多个应用程序在多个平台上实现。Microsoft Office(2007、2003、XP、2000)、OpenOffice Novell Edition、开源项目 Gnumeric、Neo-Office 2.1 和 PalmOS (Dataviz) 已经支持 Open XML。Corel 已经宣布在 WordPerfect 2007 中提供 Open XML 支持,全球的开发人员 正在使用 OpenXML 构建解决方案。

  Open XML 的标准化工作是由 Ecma International 通过其技术委员会 45 (TC45) 执行的,来自 Apple、Barclays Capital、BP、The British Library、Essilor、Intel、Microsoft、NextPage、Novell、Statoil、Toshiba 和 United States Library of Congress 的代表参与了该项工作。该标准旨在提供现有 ISO 标准所无法提供的独特好处,其中包括能够实现从现有二进制格式向基于 XML 的格式的高保真移植。

二:OpenXml Sdk 安装

  下载并安装OpenXMLSDKv2.msiOpenXMLSDKTool.msi,下载地址:https://www.microsoft.com/en-us/download/details.aspx?displaylang=en&id=5124

  

  官方SDK文档:

  

三:OpenXml Sdk 使用(新建项目)

  打开vs新建项目OpenXmlWord,引用DocumentFormat.OpenXml.dll 和 WindowsBase.dll,如下如

      

  新建word模板(word模板.docx)

  

四:OpenXml Sdk 使用(插入简单文本)

  这里主要根据插入书签(BookMark)的方式来定位位置,打开word模板.docx分别在‘公司名称’和‘公司简介’中插入两个书签。

  

  

  InsertSimpleText方法:

  

/// <summary>
///
/// </summary>
/// <param name="filepPath"></param>
/// <param name="Dictionary"></param>
public static void InsertSimpleText(string filepPath, Dictionary<string, string> dictionary)
{
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepPath, true))
{
List<BookmarkStart> allBookmarkStart = wordprocessingDocument.MainDocumentPart.RootElement.Descendants<BookmarkStart>().ToList();
foreach (KeyValuePair<string, string> keyValuePair in dictionary)
{
foreach (BookmarkStart bookmarkStart in allBookmarkStart)
{
if (bookmarkStart.Name.Value == keyValuePair.Key)
{
InsertIntoBookmark(bookmarkStart,keyValuePair.Value);
break;
}
}
}
}
}
 /// <summary>
/// 更换书签单一文本内容
/// </summary>
/// <param name="bookmarkStart">书签</param>
/// <param name="text">书签内容文本</param>
private static void InsertIntoBookmark(BookmarkStart bookmarkStart, string text)
{
OpenXmlElement elem = bookmarkStart.NextSibling();
while (elem != null && !(elem is BookmarkEnd))
{
OpenXmlElement nextElem = elem.NextSibling();
elem.Remove();
elem = nextElem;
}
bookmarkStart.Parent.InsertAfter<DocumentFormat.OpenXml.Wordprocessing.Run>(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(text)), bookmarkStart);
}

  

五:OpenXml Sdk 使用(插入图片)

  根据步骤四中新建2个图片书签位置,具体代码如下:

  

  

 /// <summary>
///
/// </summary>
/// <param name="filepPath"></param>
/// <param name="dictionary"></param>
public static void InsertImage(string filepPath, Dictionary<string, string> dictionary,byte [] byteArrary=null)
{
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepPath, true))
{
List<BookmarkStart> allBookmarkStart = wordprocessingDocument.MainDocumentPart.RootElement.Descendants<BookmarkStart>().ToList();
{
foreach (KeyValuePair<string, string> keyValuePair in dictionary)
{
foreach (BookmarkStart bookmarkStart in allBookmarkStart)
{
if (bookmarkStart.Name.Value == keyValuePair.Key)
{
byte[] imageByte = Convert.FromBase64String(keyValuePair.Value);
MainDocumentPart mainPart = wordprocessingDocument.MainDocumentPart;
ImagePart imagePart = mainPart.AddImagePart(ImagePartType.Jpeg);
Stream stream = new MemoryStream(imageByte);
if (byteArrary != null)
{
stream = new MemoryStream(byteArrary);
}
imagePart.FeedData(stream);
AddImageToBody(wordprocessingDocument, wordprocessingDocument.MainDocumentPart.GetIdOfPart(imagePart), bookmarkStart);
break;
}
}
}
}
}
}
  /// <summary>
///
/// </summary>
/// <param name="wordDoc"></param>
/// <param name="relationshipId"></param>
/// <param name="bookmarkStart"></param>
private static void AddImageToBody(WordprocessingDocument wordDoc, string relationshipId, BookmarkStart bookmarkStart)
{
// Define the reference of the image.
var element =
new Drawing(
new Inline(
new Extent() { Cx = 4900000L, Cy = 3920000L }, // 调节图片大小
new EffectExtent()
{
LeftEdge = 0L,
TopEdge = 0L,
RightEdge = 0L,
BottomEdge = 0L
},
new DocProperties()
{
Id = (UInt32Value)1U,
Name = "Picture 1"
},
new DocumentFormat.OpenXml.Drawing.Wordprocessing.NonVisualGraphicFrameDrawingProperties(
new GraphicFrameLocks() { NoChangeAspect = true }),
new Graphic(
new GraphicData(
new DocumentFormat.OpenXml.Drawing.Pictures.Picture(
new PIC.NonVisualPictureProperties(
new PIC.NonVisualDrawingProperties()
{
Id = (UInt32Value)0U,
Name = "New Bitmap Image.jpg"
},
new DocumentFormat.OpenXml.Drawing.Pictures.NonVisualPictureDrawingProperties()),
new DocumentFormat.OpenXml.Drawing.Pictures.BlipFill(
new DocumentFormat.OpenXml.Drawing.Blip(
new DocumentFormat.OpenXml.Drawing.BlipExtensionList(
new DocumentFormat.OpenXml.Drawing.BlipExtension()
{
Uri =
"{28A0092B-C50C-407E-A947-70E740481C1C}"
})
)
{
Embed = relationshipId,
CompressionState =
DocumentFormat.OpenXml.Drawing.BlipCompressionValues.Print
},
new DocumentFormat.OpenXml.Drawing.Stretch(
new DocumentFormat.OpenXml.Drawing.FillRectangle())),
new PIC.ShapeProperties(
new DocumentFormat.OpenXml.Drawing.Transform2D(
new A.Offset() { X = 0L, Y = 0L },
new A.Extents() { Cx = 990000L, Cy = 792000L }), //与上面的对准
new A.PresetGeometry(
new A.AdjustValueList()
) { Preset = A.ShapeTypeValues.Rectangle }))
) { Uri = "http://schemas.openxmlformats.org/drawingml/2006/picture" })
)
{
DistanceFromTop = (UInt32Value)0U,
DistanceFromBottom = (UInt32Value)0U,
DistanceFromLeft = (UInt32Value)0U,
DistanceFromRight = (UInt32Value)0U,
EditId = "50D07946"
});
//bookmarkStart.InsertAfterSelf(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(element)));
//bookmarkStart.Parent.InsertAfter<DocumentFormat.OpenXml.Wordprocessing.Run>(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(element)), bookmarkStart);
bookmarkStart.Parent.InsertAfter<DocumentFormat.OpenXml.Wordprocessing.Run>(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Run(element)), bookmarkStart);
}

 注:  图片的长度和宽度都乘以9525之后导入到word里的图片显示为100%。 

六:OpenXml Sdk 使用(根据表格写入数据)

  首先给已有表格插入书签

  

  

/// <summary>
///
/// </summary>
/// <param name="filepPath"></param>
/// <param name="configModel"></param>
/// <param name="dataModelList"></param>
public static void InsertTable(string filepPath, ConfigModel configModel, List<TableDataModel> dataModelList)
{
using (WordprocessingDocument wordprocessingDocument = WordprocessingDocument.Open(filepPath, true))
{
Body body = wordprocessingDocument.MainDocumentPart.Document.Body;
List<BookmarkStart> allBookmarkStart = wordprocessingDocument.MainDocumentPart.RootElement.Descendants<BookmarkStart>().ToList();
//通过索引获得table
//var table = body.Elements<DocumentFormat.OpenXml.Wordprocessing.Table>().ElementAt(configModel.Index);
//通过标签获得table
BookmarkStart bookmarkStart = allBookmarkStart.Find(a => a.Name.Value == configModel.tableBookMark);
if (bookmarkStart == null)
return;
var table = bookmarkStart.Parent.Parent.Parent.Parent; //List<DocumentFormat.OpenXml.Wordprocessing.TableRow> rowList = table.Elements<DocumentFormat.OpenXml.Wordprocessing.TableRow>().ToList();
//row = rowList[1].Clone() as DocumentFormat.OpenXml.Wordprocessing.TableRow;
foreach (TableDataModel tableDataModel in dataModelList)
{
var row = table.Elements<DocumentFormat.OpenXml.Wordprocessing.TableRow>().ElementAt(configModel.StartRowIndex).Clone() as DocumentFormat.OpenXml.Wordprocessing.TableRow;
var cells = row.Elements<DocumentFormat.OpenXml.Wordprocessing.TableCell>();
for (int i = 0; i < cells.Count(); i++)
{
var cell = cells.ElementAt(i);
//DocumentFormat.OpenXml.Wordprocessing.TableCell cellCreate = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
//cellCreate.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(DateTime.Now.ToString()))));
//row.Append(cell);
//cell = cellCreate; DocumentFormat.OpenXml.Wordprocessing.Paragraph tmpPa = cell.Elements<DocumentFormat.OpenXml.Wordprocessing.Paragraph>().First();
var tmpRuns = tmpPa.Elements<DocumentFormat.OpenXml.Wordprocessing.Run>();
if (tmpRuns.Count() <= 0)
{
tmpPa.Remove();
tmpPa = new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(" ")));
//cell.RemoveAllChildren();
cell.Append(tmpPa); }
var tmpRun = tmpPa.Elements<DocumentFormat.OpenXml.Wordprocessing.Run>().First();
var tmpText = tmpRun.Elements<DocumentFormat.OpenXml.Wordprocessing.Text>().First(); //获取属性值
Type type = tableDataModel.GetType();
string propertyKey = "Property" + (i + 1);
System.Reflection.PropertyInfo propertyInfo = type.GetProperty(propertyKey); //获取指定名称的属性
object objValue = propertyInfo.GetValue(tableDataModel, null);
if (objValue != null)
{
tmpText.Text = objValue.ToString();
}
else
{
tmpText.Text = "-";
}
}
//DocumentFormat.OpenXml.Wordprocessing.TableRow rowx = new DocumentFormat.OpenXml.Wordprocessing.TableRow();
//string[] rowArray = { "","","",""};
//foreach (string strCell in rowArray)
//{
// DocumentFormat.OpenXml.Wordprocessing.TableCell cell = new DocumentFormat.OpenXml.Wordprocessing.TableCell();
// cell.Append(new DocumentFormat.OpenXml.Wordprocessing.Paragraph(new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.Text(strCell))));
// row.Append(cell);
//}
//table.Append(rowx); var lastRow = table.Elements<DocumentFormat.OpenXml.Wordprocessing.TableRow>().Last();
table.InsertAfter<DocumentFormat.OpenXml.Wordprocessing.TableRow>(row, lastRow);
}
//最后删除startIndex行
table.Elements<DocumentFormat.OpenXml.Wordprocessing.TableRow>().ElementAt(configModel.StartRowIndex).Remove();
}
}

  最后源码下载地址:http://files.cnblogs.com/files/sunyj/OpenXmlWord.rar

  相关资料网址:https://msdn.microsoft.com/en-us/library/bb497430(office.14).aspx

OpenXml Sdk 根据Word模板导出到word的更多相关文章

  1. Net Core DocXCore 实现word模板导出

    实际工作中,往往有这样的需求,需要导出word,还有各种各样的样式,于是有了word模板导出. 实现以下几个需求: 1.表单导出 2.表格导出 3.表单表格混合导出 4.实际用例测试 解决方案: 实现 ...

  2. SpringBoot集成文件 - 如何基于POI-tl和word模板导出庞大的Word文件?

    前文我们介绍了通过Apache POI通过来导出word的例子:那如果是word模板方式,有没有开源库通过模板方式导出word呢?poi-tl是一个基于Apache POI的Word模板引擎,也是一个 ...

  3. 8、jeecg 笔记之 自定义word 模板导出(一)

    1.前言 jeecg 中已经自带 word 的导出导出功能,其所使用的也是 easypoi,尽管所导出的 word 能满足大部分需求, 但总是有需要用到自定义 word导出模板,下文所用到的皆是 ea ...

  4. word模板导出的几种方式:第一种:占位符替换模板导出(只适用于word中含有表格形式的)

    1.占位符替换模板导出(只适用于word中含有表格形式的): /// <summary> /// 使用替换模板进行到处word文件 /// </summary> public ...

  5. .net core 使用NPOI填充Word模板导出Word

    最近工作用到在Word模板插入数据库数据,导出一个带数据的Word文件,想起来之前操作Word都是用微软提供的Microsoft.Office.Interop.Word,而在最新的..NET CORE ...

  6. 利用模板导出文件(二)之jacob利用word模板导出word文件(Java2word)

    https://blog.csdn.net/Fishroad/article/details/47951061?locationNum=2&fps=1 先下载jacob.jar包.解压后将ja ...

  7. C# 使用Word模板导出数据

    使用NPOI控件导出数据到Word模板中方式: 效果如下: Word模板: 运行结果: 实现如下: Student.cs using System; using System.Collections. ...

  8. word模板导出的几种方式:第三种:标签替换(DocX组件读取与写入Word)

    dll文件下载地址:https://files-cdn.cnblogs.com/files/daizhipeng/DocX.rar DocX wordDocumentOld = DocX.Load(S ...

  9. java根据word模板导出word文件

    1.word模板文件处理,如下图所示在word 文档中填值的地方写入占位变量 2.将word文档另存为xml文件.编辑如下图,找到填写的占位,修改为${bcrxm}格式 3.将文件后缀名改为.ftl文 ...

随机推荐

  1. AngularJs2 学习之路-笔记1-Atscript Ts ES6包含关系

    Atscript 这门新的语言是由谷歌的Angular团队弄出来的 就是为了编写ng2.0 ng2是个极具前瞻性的尝试 这种激进的革新在于对未来标准的迎合 ng2的标准包括了如下:1 module 2 ...

  2. 汽车遥控钥匙HCS101/HCS200/HCS201/HCS300芯片解密

    汽车遥控钥匙芯片解密ic解密型号: HCS101 | HCS200 | HCS201 | HCS201T | HCS300 | HCS300T HCS301 | HCS301T | HCS360 |  ...

  3. java 猜数字游戏

    作用:猜数字游戏.随机产生1个数字(1~10),大了.小了或者成功后给出提示. 语言:java 工具:eclipse 作者:潇洒鸿图 时间:2016.11.10 >>>>> ...

  4. WinServer 2008 远程桌面连接设置

    WinServer 2008 远程桌面连接设置   1.在服务器端启用远程桌面>>计算机--右键--管理 看远程桌面是否已经启用,若未启用则启用它.配置远程桌面,勾选允许任意版本远程桌面的 ...

  5. 北京电子科技学院(BESTI)实验报告3

    北京电子科技学院(BESTI)实验报告3 课程: 信息安全系统设计基础 班级:1452.1453 姓名:(按贡献大小排名)周恩德 .郑凯杰 学号:(按贡献大小排名)20145217 .201453 指 ...

  6. 【BZOJ1087】 [SCOI2005]互不侵犯King 状压DP

    经典状压DP. f[i][j][k]=sum(f[i-1][j-cnt[k]][k]); cnt[i]放置情况为i时的国王数量 前I行放置情况为k时国王数量为J #include <iostre ...

  7. 解决Winform应用程序中窗体背景闪烁的问题

    本文转载:https://my.oschina.net/Tsybius2014/blog/659742 我的操作系统是Win7,使用的VS版本是VS2012,文中的代码都是C#代码. 这几天遇到一个问 ...

  8. (转)完全用GNU/Linux工作 by 王珢

    完全用GNU/Linux工作 王珢      (看完这篇博文,非常喜欢王珢的这篇博客,也我坚定了学gnu/linux的决心,并努力去按照国外的计算机思维模式去学习编程提高自己.看完这篇文章令我热血沸腾 ...

  9. django manytomany

    转载:http://my.oschina.net/u/572994/blog/105280 例如有如下模型 models.py ? 1 2 3 4 5 6 7 from django.db impor ...

  10. C 格式输出

    1 一般格式    printf(格式控制,输出表列)    例如:printf("i=%d,ch=%c\n",i,ch);    说明:    (1) “格式控制”是用双撇号括起 ...