一: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. <更新日期03-31-2016> 复利计算5.0 <已改进>

    作业要求: 1.客户说:帮我开发一个复利计算软件. 完成复利公式计算程序,并成功PUSH到github上. 客户提出: 2.如果按照单利计算,本息又是多少呢? 3.假如30年之后要筹措到300万元的养 ...

  2. CodeForces 103D 分块处理

    题目链接:http://codeforces.com/problemset/problem/103/D 题意:给定一个长度为n的序列.然后q个询问.每个询问为(a,b),表示从序列第a项开始每b项的加 ...

  3. java-集合1

    浏览以下内容前,请点击并阅读 声明 集合(collection),可以看做一个容器,是将多个元素组合成一个单位的对象.集合用来存储,检索,操作,交互一些聚集的数据.通常,集合用来表示一个组的数据,就像 ...

  4. Bungee Jumping[HDU1155]

    Bungee JumpingTime Limit: 2000/1000 MS (Java/Others) Memory Limit: 65536/32768 K (Java/Others)Total ...

  5. css3 缓动公式

    var easingMap = { "linear": [0.250, 0.250, 0.750, 0.750], "ease": [0.250, 0.100, ...

  6. unity3d的GUI元素的界面坐标系统总结(有公式)

    GUIText 和GUITexture 1.GUIText 锚点(Anchor)的概念我就不介绍了.像NGUI和tookit2d还有 Cocos2d中都有这个重要的概念,对于图片我们可以认为是图片自身 ...

  7. 获取文件hash值

    public string getFilesMD5Hash(string file)        {            //MD5 hash provider for computing the ...

  8. 函数Curry化

    之前写过一个函数Curry化的小文章 那会儿对Curry化的理解不够深,平时遇到的需要Curry化的例子也比较少,今天,重新整理这个问题 函数Curry化,其实就是将一个参数非常多的函数,在大多数参数 ...

  9. mysql延迟查询, 覆盖索引使用例子

    引用自 'mysql高性能' 5.3.6章节 不能使用覆盖索引的情况 :  解决办法 : 

  10. 利用JS生成01010101……长度可控的序列

    function ab(d){ var a = []; var x = 1 ; for (var i = 0; i < d; i++) { if (x == 0) { x = x + 1; } ...