一: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.msi和OpenXMLSDKTool.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