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();
}

  

/// <summary>
///
/// </summary>
/// <param name="sourceFile"></param>
/// <param name="destinationFile"></param>
private void setWord(string sourceFile, string destinationFile)
{
File.Copy(sourceFile, destinationFile, true);
using (WordprocessingDocument document = WordprocessingDocument.Open(destinationFile, true))
{
// Change the document type to Document DocumentFormat.OpenXml.WordprocessingDocumentType // DocumentFormat.OpenXml.WordprocessingDocumentType doc = new WordprocessingDocumentType();
document.ChangeDocumentType(DocumentFormat.OpenXml.WordprocessingDocumentType.Document);
// Get the MainPart of the document
MainDocumentPart mainPart = document.MainDocumentPart;
// Get the Document Settings Part
DocumentSettingsPart documentSettingPart1 = mainPart.DocumentSettingsPart;
// Create a new attachedTemplate and specify a relationship ID
AttachedTemplate attachedTemplate1 = new AttachedTemplate() { Id = "relationId1" };
// Append the attached template to the DocumentSettingsPart
documentSettingPart1.Settings.Append(attachedTemplate1);
// Add an ExternalRelationShip of type AttachedTemplate.
// Specify the path of template and the relationship
documentSettingPart1.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/attachedTemplate", new Uri(sourceFile, UriKind.Absolute), "relationId1"); // Get a list of bookmarks
IDictionary<String, BookmarkStart> bookmarkMap = new Dictionary<String, BookmarkStart>();
foreach (BookmarkStart bookmarkStart in mainPart.RootElement.Descendants<BookmarkStart>())
{
bookmarkMap[bookmarkStart.Name] = bookmarkStart;
}
// Make changes to bookmarks
foreach (BookmarkStart bookmarkStart in bookmarkMap.Values)
{
if (bookmarkStart.Name == "WorkOrderNo")
{
string WorkOrderNum = "WorkOrderNo";
DocumentFormat.OpenXml.Wordprocessing.Text text = new DocumentFormat.OpenXml.Wordprocessing.Text(WorkOrderNum);
DocumentFormat.OpenXml.Wordprocessing.FontSize WOFontSize = new DocumentFormat.OpenXml.Wordprocessing.FontSize();
WOFontSize.Val = "28";
DocumentFormat.OpenXml.Wordprocessing.Run run = new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new DocumentFormat.OpenXml.Wordprocessing.Bold(), WOFontSize));
run.Append(text);
bookmarkStart.InsertAfterSelf(run);
}
else if (bookmarkStart.Name == "BillingCode")
{
string BillingCode = "BillingCode";
DocumentFormat.OpenXml.Wordprocessing.Text text = new DocumentFormat.OpenXml.Wordprocessing.Text(BillingCode);
DocumentFormat.OpenXml.Wordprocessing.FontSize WOFontSize = new DocumentFormat.OpenXml.Wordprocessing.FontSize();
WOFontSize.Val = "28";
DocumentFormat.OpenXml.Wordprocessing.Run run = new DocumentFormat.OpenXml.Wordprocessing.Run(new DocumentFormat.OpenXml.Wordprocessing.RunProperties(new DocumentFormat.OpenXml.Wordprocessing.Bold(), WOFontSize));
run.Append(text);
bookmarkStart.InsertAfterSelf(run);
}
}
// Save the document
mainPart.Document.Save();
}
}
/// <summary>
/// To search and replace content in a document part.
/// </summary>
/// <param name="document"></param>
/// <param name="dict"></param>
public static void SearchAndReplace(string document, Dictionary<string, string> dict)
{
using (WordprocessingDocument wordDoc = WordprocessingDocument.Open(document, true))
{
string docText = null;
using (StreamReader sr = new StreamReader(wordDoc.MainDocumentPart.GetStream()))
{
docText = sr.ReadToEnd();
} foreach (KeyValuePair<string, string> item in dict)
{
Regex regexText = new Regex(item.Key);
docText = regexText.Replace(docText, item.Value);
} using (StreamWriter sw = new StreamWriter(
wordDoc.MainDocumentPart.GetStream(FileMode.Create)))
{
sw.Write(docText);
} }
}

  

Csharp: create word file using Open XML SDK 2.5的更多相关文章

  1. Csharp: read excel file using Open XML SDK 2.5

    using System; using System.Collections.Generic; using System.ComponentModel; using System.Data; usin ...

  2. User Word Automation Services and Open XML SDK to generate word files in SharePoint2010

    SharePoint 2010 has established a new service called "Word Automation Services" to operate ...

  3. Embedding Documents in Word 2007 by Using the Open XML SDK 2.0 for Microsoft Office

    Download the sample code This visual how-to article presents a solution that creates a Word 2007 doc ...

  4. Open Xml SDK Word模板开发最佳实践(Best Practice)

    1.概述 由于前面的引文已经对Open Xml SDK做了一个简要的介绍. 这次来点实际的——Word模板操作. 从本质上来讲,本文的操作都是基于模板替换思想的,即,我们通过替换Word模板中指定元素 ...

  5. 下载和编译 Open XML SDK

    我们需要一些工具来开始 Open XML 的开发. 开发工具 推荐的开发工具是 Visual Studio 社区版. 开发工具:Visual Studio Community 2013 下载地址:ht ...

  6. 【转】Open XML SDK class structure

    Open XML SDK class structure March 27, 2012 by Vincent I’ve gotten a few questions on the class stru ...

  7. Open Xml SDK 引文

    什么是Open Xml SDK? 什么是Open Xml? 首先,我们得知道,Open Xml为何物? 我们还是给她起个名字——就叫 “开放Xml”,以方便我们中文的阅读习惯.之所以起开放这个名字,因 ...

  8. Open XML SDK 在线编程黑客松

    2015年2月10日-3月20日,开源社 成员 微软开放技术,GitCafe,极客学院联合举办" Open XML SDK 在线编程黑客松 ",为专注于开发提高生产力的应用及服务的 ...

  9. C# Word转PDF/HTML/XML/XPS/SVG/EMF/EPUB/TIFF

    一款有着强大的文档转换功能的工具,无论何时何地都会是现代办公环境极为需要的.在本篇文章中,将介绍关于Word文档的转换功能(Word转XPS/SVG/EMF/EPUB/TIFF).希望方法中的代码能为 ...

随机推荐

  1. iOS WKWebView详解

    UIWebView就不用说了,这个过时了,现在iOS8以后建议都使用WKWebView. WKWebView 是现代 WebKit API 在 iOS 8 和 OS X Yosemite 应用中的核心 ...

  2. [原]OpenGL基础教程(二)多边形绘制

    上篇介绍了最基本的三角形绘制,本篇介绍如何使用索引的方式绘制多边行. 为什么要使用索引方式,总体来说提高性能.如何提高:使用顶点数组的好处是避免大量的函数调用.即避免每画一个顶点就调用1次glVert ...

  3. ssh框架搭建错误集合

    1,把jsp放入到WEB-INF/view目录下,struts2.xml配置<result name="success">/WEB-INF/view/home.jsp& ...

  4. Objective-C学习备忘录:Clang编译器编译运行Objective-C代码

    我们都知道可以通过Apple公司的Xcode工具来学习Objective-C编程语言,但是能不能脱离XCode这个IDE进行Objective-C学习呢?当然是可以的.首先作为计算机科班出身的程序员都 ...

  5. Unity3d游戏中自定义贝塞尔曲线编辑器[转]

    关于贝塞尔曲线曲线我们再前面的文章提到过<Unity 教程之-在Unity3d中使用贝塞尔曲线>,那么本篇文章我们来深入学习下,并自定义实现贝塞尔曲线编辑器,贝塞尔曲线是最基本的曲线,一般 ...

  6. 转:php park、unpark、ord 函数使用方法(二进制流接口应用实例)

    在工作中,我也逐渐了解到park,unpark,ord对于二进制字节处理的强大. 下面我逐一介绍它们.     park,unpark,ord这3个函数,在我们工作中,用到它们的估计不多. 我在最近一 ...

  7. SQL Server 问题 1 - SQL Server encountered error 0x80070422/0x8007042d

    今天执行SQL Server 2014的full-text search 查询操作:select * from table where contains(summary, 'smith') 报出如下错 ...

  8. efwplus框架介绍

    此框架得到博客园大神@张善友的关注,建议我写一篇此框架的最新介绍,好在@dotNet跨平台公众号上推荐给大家,得到大神的指示当然激动,马不停蹄的赶出此文,供大家参考!   一.使用efwplus框架的 ...

  9. [原创]与来自facebook的朋友交流

    与来自facebook的朋友交流 老板的儿子在facebook工作,现在正好有个假期回来,老总让我们部门与之进行一次交流.其实主要是他讲一下那边情况,然后我们准备些问题,多扩展一下我们见识. 流程 交 ...

  10. 代码演示 .NET 4.5 自带的 ReadonlyCollection 的使用

    代码如下: 1. using System; using System.Collections.Generic; using System.Linq; using System.Text; using ...