Csharp:create Word file using the Open XML SDK 2.5

Source: Internet
Author: User

Using system;using system.collections.generic;using system.componentmodel;using system.data;using System.Drawing; Using system.linq;using system.text;using system.windows.forms;using documentformat.openxml;using Documentformat.openxml.packaging;using documentformat.openxml.wordprocessing;using Documentformat.openxml.spreadsheet;using system.io;using system.io.packaging;using System.Xml;using System.xml.linq;namespace openxmloficedemo{//<summary>///open Xml SDK 2.0 WORD https://msdn.microsoft.com/ en-us/library/office/gg490656 (v=office.14). aspx///open XML SDK 2.5 WORD https://msdn.microsoft.com/en-us/library/ Office/ff478541.aspx//</summary> public partial class Form2:form {//<summary>/        </summary> public Form2 () {InitializeComponent ();        }//<summary>///</summary>//<param name= "Sender" ></param> <paraM name= "e" ></param> private void Form2_load (object sender, EventArgs e) {//Open document Add Table            String Timemark = DateTime.Now.ToString ("Yyyymmddhhmmss"); String fileName = Path.Combine (Environment.getfolderpath (Environment.SpecialFolder.Desktop), "National substitute Teacher's information collection template" + ".  Docx ");  "Geovindu" + Timemark//wdaddtable (fileName, New string[,]//{//{"Tu-wen", "Du"},//{"Texas", "TX"},//{"California", "CA"},//{"New Yo        RK "," NY "},//{" New York "," NY "},//{" Massachusetts "," MA "}//}); }//<summary>///</summary>//<param name= "Sender" ></par        am>//<param name= "E" ></param> private void Button1_Click (object sender, EventArgs e) {//Change a existing property ' s value or createA new one with the supplied value WDSetCustomProperty ("C:\\demo.docx", "completed", false, Propertytypes.yesno); Change an existing property ' s value or create a new one with the supplied value Wdsetcustomprope        Rty ("C:\\demo.docx", "Completed", New DateTime (1, 1), propertytypes.datetime);        }//<summary>///</summary>//<param name= "Sender" ></param>            <param name= "E" ></param> private void button2_click (object sender, EventArgs e) {            String Timemark = DateTime.Now.ToString ("Yyyymmddhhmmss"); String fileName = Path.Combine (Environment.getfolderpath (Environment.SpecialFolder.Desktop), "Geovindu" + Timemark + "            . docx "); Createworddoc (FileName, "Geovin", new string[,] {"Tu", "Du"}, {"T Exas "," TX "}, {" California "," CA "}, {" NewYork "," NY "}, {" New York "," NY "}, {" Massachusetts "," MA "}}); }//<summary>///</summary>/<param name= "FileName" ></param            >//<returns></returns> public static XElement Wdretrievetoc (string fileName) {            XElement TOC = null; using (var document = Wordprocessingdocument.open (FileName, False)) {var Docpart = document.                Maindocumentpart;                var doc = docpart.document; Openxmlelement block = doc.                  Descendants<docpartgallery> (). Where (b = B.val.hasvalue && (b.val.value = = "Table of Contents")).                FirstOrDefault ();                    if (block! = NULL) {//enclosing sdtblock and return that XML. while (block! = NULL) && (! ( Block is Sdtblock)))                   {block = block.                    Parent; } TOC = new XElement ("TOC", block.                OuterXml);        }} return TOC;  }///<summary>///Open Word Add table Word//Take the data from a 2-dimensional array and build a        Table at the///end of the supplied document. </summary>//<param name= "FileName" ></param>//<param name= "Data" ></param > public static void Wdaddtable (String fileName, string[,] data) {using (var document = Word Processingdocument.open (filename, true))//wordprocessingdocument.create (filename, Wordprocessingdocumenttype.document)) {var doc = Document.                Maindocumentpart.document;                DocumentFormat.OpenXml.Wordprocessing.Table Table = new DocumentFormat.OpenXml.Wordprocessing.Table (); Tableproperties props = new TableprOperties (New Tableborders (New DocumentFormat.OpenXml.Wordprocessing.TopBorder                        {Val = new enumvalue<bordervalues> (bordervalues.single),                    Size = A, new DocumentFormat.OpenXml.Wordprocessing.BottomBorder {Val = new enumvalue<bordervalues> (bordervalues.single), Size = 1                        2}, new DocumentFormat.OpenXml.Wordprocessing.LeftBorder {                    Val = new Enumvalue<bordervalues> (bordervalues.single), Size = 12                        }, new DocumentFormat.OpenXml.Wordprocessing.RightBorder {                    Val = new Enumvalue<bordervalues> (bordervalues.single), Size = 12 }, NEW Insidehorizontalborder {Val = new enumvalue<bordervalues> (bordervalues.                    Single), Size = A, new Insideverticalborder {Val = new enumvalue<bordervalues> (bordervalues.single), Size =                12})); Table.                Appendchild<tableproperties> (props); for (var i = 0; I <= data. GetUpperBound (0);                    i++) {var tr = new TableRow (); for (var j = 0; J <= data. GetUpperBound (1);                        J + +) {var TC = new TableCell (); Tc. Append (New Paragraph new DocumentFormat.OpenXml.Wordprocessing.Run (New DocumentFormat.OpenXml.Wordprocessing.Text                        (Data[i, J])));                        Assume you want columns is automatically sized. Tc. Append (New TAblecellproperties (new Tablecellwidth {Type = Tablewidthunitvalues.auto})); Tr.                    Append (TC); } table.                Append (TR); } doc.                Body.append (table); Doc.            Save (); }}///<summary>//Create Word document, add Table///</summary>//<param name= "file Path "></param>//<param name=" MSG "></param>//<param name=" Data "&GT;&LT;/PARAM&G        T public static void Createworddoc (string filepath, String msg, string[,] data) {using (Wordprocessingdoc Ument doc = wordprocessingdocument.create (filepath, wordprocessingdocumenttype.document)) {//A                 DD a main document part. Maindocumentpart Mainpart = doc.                Addmaindocumentpart ();                Create the document structure and add some text. Mainpart.document = new DocumeNT (); Body BODY = new body ();                DocumentFormat.OpenXml.Wordprocessing.Table Table = new DocumentFormat.OpenXml.Wordprocessing.Table (); Tableproperties props = new Tableproperties (new Tableborders (New DOCU MentFormat.OpenXml.Wordprocessing.TopBorder {Val = new Enumvalue<bordervalue S> (bordervalues.single), Size = A, new DOCUMENTFORMAT.O PenXml.Wordprocessing.BottomBorder {Val = new enumvalue<bordervalues> (Bor Dervalues.single), Size = A, new DocumentFormat.OpenXml.Wo Rdprocessing.                        Leftborder {Val = new enumvalue<bordervalues> (bordervalues.single), Size = A, new DOCUMENTFORMAT.OPenXml.Wordprocessing.RightBorder {Val = new enumvalue<bordervalues> (Bord                    Ervalues.single), Size = A, new Insidehorizontalborder                        {Val = new enumvalue<bordervalues> (bordervalues.single),                        Size = A, new Insideverticalborder {                Val = new Enumvalue<bordervalues> (bordervalues.single), Size = 12}); Table.                Appendchild<tableproperties> (props); for (var i = 0; I <= data. GetUpperBound (0);                    i++) {var tr = new TableRow (); for (var j = 0; J <= data. GetUpperBound (1);                        J + +) {var TC = new TableCell (); Tc. Append (New Paragraph (New DocumenTFormat.OpenXml.Wordprocessing.Run (New DocumentFormat.OpenXml.Wordprocessing.Text (Data[i, J])));                        Assume you want columns is automatically sized. Tc.                        Append (New Tablecellproperties (new Tablecellwidth {Type = Tablewidthunitvalues.auto})); Tr.                    Append (TC); } table.                Append (TR); }//appending table to body body.                Append (table);                and body to the document MainPart.Document.Append (body);                 Save changes to the main document part.             MainPart.Document.Save ();        }}///<summary>//Delete headers and footers from a document. </summary>//<param name= "DocName" ></param> public static void Wdremoveheadersfooter S (string docname) {//Given a document NAMe, remove all headers and footers. using (wordprocessingdocument Wddoc = Wordprocessingdocument.open (DocName, True)) {var docpart                = Wddoc.maindocumentpart; if (DocPart.HeaderParts.Count () > 0 | | docPart.FooterParts.Count () > 0) {//Remov                    E Header and footer parts.                    Docpart.deleteparts (Docpart.headerparts);                    Docpart.deleteparts (Docpart.footerparts);                    Document doc = docpart.document;                    Remove references to the headers and footers.                      This requires digging into the XML content//Of the Document:var headers = Doc. Descendants

  

Csharp:create Word file using the Open XML SDK 2.5

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.