码迷,mamicode.com
首页 > 其他好文 > 详细

Csharp: create word file using Open XML SDK 2.5

时间:2015-08-21 17:05:27      阅读:288      评论:0      收藏:0      [点我收藏+]

标签:

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)
        {

            //打开文档添加表格
            //string timeMark = DateTime.Now.ToString("yyyyMMddHHmmss");
            //string fileName = Path.Combine(Environment.GetFolderPath(Environment.SpecialFolder.Desktop), "全国民代课教师的信息收集模板" + ".docx");  // "geovindu" + timeMark  
            //WDAddTable(fileName, new string[,] 
            //  { 
            //      { "涂聚文",  "Du" }, 
            //      { "Texas",  "TX" }, 
            //      { "California", "CA" }, 
            //      { "New York", "NY" }, 
            //      { "New York", "NY" }, 
            //      { "Massachusetts", "MA" } 
            //  });

        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void button1_Click(object sender, EventArgs e)
        {
            // Change an existing property‘s value or create a 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
            WDSetCustomProperty("C:\\demo.docx", "Completed",new DateTime(2008, 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[,] 
              { 
                  { "涂聚文",  "Du" }, 
                  { "Texas",  "TX" }, 
                  { "California", "CA" }, 
                  { "New York", "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)
                {
                    // Back up to the enclosing SdtBlock and return that XML.
                    while ((block != null) && (!(block is SdtBlock)))
                    {
                        block = block.Parent;
                    }
                    TOC = new XElement("TOC", block.OuterXml);
                }
            }
            return TOC;
        }
        /// <summary>
        /// 打开WORD添加表格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 =  WordprocessingDocument.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 = 12
                    },
                    new DocumentFormat.OpenXml.Wordprocessing.BottomBorder
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12
                    },
                    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 = 12
                    },
                    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 that are automatically sized.
                        tc.Append(new TableCellProperties(
                          new TableCellWidth { Type = TableWidthUnitValues.Auto }));
                        tr.Append(tc);
                    }
                    table.Append(tr);
                }
                doc.Body.Append(table);
                doc.Save();
            }
        }

        /// <summary>
        /// 创建WORD文档,添加表格
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="msg"></param>
        /// <param name="data"></param>
        public static void CreateWordDoc(string filepath, string msg, string[,] data)
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                // Add 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 DocumentFormat.OpenXml.Wordprocessing.TopBorder
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12
                    },
                    new DocumentFormat.OpenXml.Wordprocessing.BottomBorder
                    {
                        Val = new EnumValue<BorderValues>(BorderValues.Single),
                        Size = 12
                    },
                    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 = 12
                    },
                    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 that are 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 WDRemoveHeadersFooters(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)
                {
                    // Remove 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<HeaderReference>().ToList();
                    foreach (var header in headers)
                    {
                        header.Remove();
                    }

                    var footers =
                      doc.Descendants<FooterReference>().ToList();
                    foreach (var footer in footers)
                    {
                        footer.Remove();
                    }
                    doc.Save();
                }
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="txt"></param>
        public static void OpenAndAddTextToWordDocument(string filepath, string txt)
        {
            // Open a WordprocessingDocument for editing using the filepath.
            WordprocessingDocument wordprocessingDocument =
                WordprocessingDocument.Open(filepath, true);

            // Assign a reference to the existing document body.
            Body body = wordprocessingDocument.MainDocumentPart.Document.Body;

            // Add new text.
            Paragraph para = body.AppendChild(new Paragraph());
            DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run());
            run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text(txt));

            // Close the handle explicitly.
            wordprocessingDocument.Close();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filepath"></param>
        /// <param name="msg"></param>
        public static void CreateWordDoc(string filepath, string msg)
        {
            using (WordprocessingDocument doc = WordprocessingDocument.Create(filepath, WordprocessingDocumentType.Document))
            {
                // Add a main document part. 
                MainDocumentPart mainPart = doc.AddMainDocumentPart();

                // Create the document structure and add some text.
                mainPart.Document = new Document();
                Body body = mainPart.Document.AppendChild(new Body());
                Paragraph para = body.AppendChild(new Paragraph());
                DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run());

                // String msg contains the text, "Hello, Word!"
                run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text(msg));
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filepath"></param>
        public static void OpenWordprocessingDocumentReadonly(string filepath)
        {
            // Open a WordprocessingDocument based on a filepath.
            using (WordprocessingDocument wordDocument =
                WordprocessingDocument.Open(filepath, false))
            {
                // Assign a reference to the existing document body.  
                Body body = wordDocument.MainDocumentPart.Document.Body;

                // Attempt to add some text.
                Paragraph para = body.AppendChild(new Paragraph());
                DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run());
                run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("Append text in body, but text is not saved - OpenWordprocessingDocumentReadonly"));

                // Call Save to generate an exception and show that access is read-only.
                // wordDocument.MainDocumentPart.Document.Save();
            }
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filepath"></param>
        public static void OpenWordprocessingPackageReadonly(string filepath)
        {
            // Open System.IO.Packaging.Package.
            Package wordPackage = Package.Open(filepath, FileMode.Open, FileAccess.Read);

            // Open a WordprocessingDocument based on a package.
            using (WordprocessingDocument wordDocument =
                WordprocessingDocument.Open(wordPackage))
            {
                // Assign a reference to the existing document body. 
                Body body = wordDocument.MainDocumentPart.Document.Body;

                // Attempt to add some text.
                Paragraph para = body.AppendChild(new Paragraph());
                DocumentFormat.OpenXml.Wordprocessing.Run run = para.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Run());
                run.AppendChild(new DocumentFormat.OpenXml.Wordprocessing.Text("Append text in body, but text is not saved - OpenWordprocessingPackageReadonly"));

                // Call Save to generate an exception and show that access is read-only.
                // wordDocument.MainDocumentPart.Document.Save();
            }

            // Close the package.
            wordPackage.Close();
        }
        /// <summary>
        /// 
        /// </summary>
        /// <param name="filepath"></param>
        public static void CreateSpreadsheetWorkbook(string filepath)
        {
            // Create a spreadsheet document by supplying the filepath.
            // By default, AutoSave = true, Editable = true, and Type = xlsx.
            SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Create(filepath, SpreadsheetDocumentType.Workbook);

            // Add a WorkbookPart to the document.
            WorkbookPart workbookpart = spreadsheetDocument.AddWorkbookPart();
            workbookpart.Workbook = new Workbook();

            // Add a WorksheetPart to the WorkbookPart.
            WorksheetPart worksheetPart = workbookpart.AddNewPart<WorksheetPart>();
            worksheetPart.Worksheet = new Worksheet(new SheetData());

            // Add Sheets to the Workbook.
            Sheets sheets = spreadsheetDocument.WorkbookPart.Workbook.AppendChild<Sheets>(new Sheets());

            // Append a new worksheet and associate it with the workbook.
            Sheet sheet = new Sheet() { Id = spreadsheetDocument.WorkbookPart.GetIdOfPart(worksheetPart), SheetId = 1, Name = "mySheet" };
            sheets.Append(sheet);

            workbookpart.Workbook.Save();

            // Close the document.
            spreadsheetDocument.Close();
        }

  

Csharp: create word file using Open XML SDK 2.5

标签:

原文地址:http://www.cnblogs.com/geovindu/p/4748350.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!