OpenXml Sdk exports data to Word according to the word template. openxmlsdk

Source: Internet
Author: User

OpenXml Sdk exports data to Word according to the word template. openxmlsdk

I. Introduction to OpenXml Sdk

Brief Introduction to the Open XML standard: Ecma Office Open XML ("Open XML") is an international Open standard for word processing documents, presentations, and workbooks, multiple applications can be implemented on multiple platforms for free. Microsoft Office (2007, 2003, XP, 2000), OpenOffice Novell Edition, Open-source project Gnumeric, Neo-Office 2.1, and PalmOS (Dataviz) already support Open XML. Corel has announced the provision of Open XML support in WordPerfect 2007, and developers around the world are using OpenXML to build a solution.

The standardization of Open XML is implemented by Ecma International through its Technical Committee 45 (TC45, representatives from Apple, Barclays Capital, BP, The British Library, Essilor, Intel, Microsoft, NextPage, Novell, Statoil, Toshiba, and United States Library of Congress participated in The work. The purpose of this standard is to provide unique benefits that existing ISO standards cannot provide, including high fidelity porting from existing binary formats to XML-based formats.

Ii. OpenXml Sdk Installation

  Download and install OpenXMLSDKv2.msi and OpenXMLSDKTool. msi,: https://www.microsoft.com/en-us/download/details.aspx? Displaylang = en & id = 5124

  

Official SDK documentation:

  

Iii. Use OpenXml Sdk (New Project)

  Open the OpenXmlWord project in vs and reference DocumentFormat. OpenXml. dll and WindowsBase. dll, as shown in the following figure.

New wordtemplate.docx)

  

4. Use OpenXml Sdk (insert simple text)

  The location is located based on the BookMark insertion method.Wordtemplate.docx inserts two bookmarks in 'Company name' and 'Company profile 'respectively.

  

  

InsertSimpleText method:

  

/// <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> /// Replace the single text content of the bookmarks /// </summary> /// <param name = "bookmarkStart"> bookmarks </param> /// <param name = "text"> bookmarkcontent 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 );}

  

V. Use OpenXml Sdk (insert image)

Create two image bookmarks according to Step 4. The Code is as follows:

  

  

 /// <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}, // adjust the image size to new rows textent () {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. offset () {X = 0L, Y = 0L}, new. extents () {Cx = 9910000l, Cy = 792000L}), // align with the above new. presetGeometry (new. adjustValueList () {Preset =. 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 );}

  

6. Use OpenXml Sdk (write data based on tables)

First, insert a bookmark to an existing table.

  

  

/// <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. M AinDocumentPart. document. body; List <BookmarkStart> allBookmarkStart = wordprocessingDocument. mainDocumentPart. rootElement. descendants <BookmarkStart> (). toList (); // obtain table by index // var table = body. elements <DocumentFormat. openXml. wordprocessing. table> (). elementAt (configModel. index); // obtain table BookmarkStart bookmarkStart = allBookmarkStart by TAG. find (a =>. name. value = configModel. tableBookMark); if (B OokmarkStart = 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 <DocumentForma T. 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 <Docum EntFormat. 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. E Lements <DocumentFormat. openXml. wordprocessing. text> (). first (); // obtain the property value Type = tableDataModel. getType (); string propertyKey = "Property" + (I + 1); System. reflection. propertyInfo propertyInfo = type. getProperty (propertyKey); // get the attribute object objValue = propertyInfo of the specified name. 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);} // Delete the startIndex row table. elements <DocumentFormat. openXml. wordprocessing. tableRow> (). elementAt (configModel. startRowIndex ). remove ();}}

Last source code: http://files.cnblogs.com/files/sunyj/OpenXmlWord.rar

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.