OpenXML概述
项目中经常需要操作word,之前的方式是采用COM接口,这个接口很不稳定,经常报错。现在开始采用OpenXML。OpenXML(OOXML)是微软在Office 2007中提出的一种新的文档格式,Office 2007中的Word、Excel、PowerPoint默认均采用OpenXML格式 。
OpenXml相对于用MS提供的COM组件来生成WORD,有如下优势:
1.相对于MS 的COM组件,因为版本带来的不兼容问题,及各种会生成WORD半途会崩溃的问题.
2.对比填满一张30多页的WORD来说(包含图,表等),用COM组件来生成会占用20秒,Openxml1秒.
3.MS Word软件太贵了,你的客户装的是开源WORD,如LibreOffice,OpenOffice.这样你就只能用Openxml生成的WORD文档,各种支持MS Word都能打开,避免客户机器上安装MS Word.
4.代码简单。用OpenXML开发word简直太方便了!!!
要做OpenXML的开发,需要了解OpenXML的基本结构。

Open XML SDK 2.0 tool
因为OpenXML的结构比较复杂,开始开发时往往不好入门,摸不清其结构。微软很贴心的提供了一个工具,Open XML SDK Productivity Tool for Microsoft Office。
下载地址
这个工具可以打开任意一个docx的文档,然后Reflect Code,得到整个文档代码,之后怎么操作直接看代码就好了,真是太方便了。
另外这个工具也提供了文档,不清楚的可以查一下文档。
代码示例
我参考上面的工具,写了一个简单的操作word的帮助类。
using System.Collections.Generic;
using System.IO;
using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Wordprocessing;
using AA = DocumentFormat.OpenXml.Drawing;
using DW = DocumentFormat.OpenXml.Drawing.Wordprocessing;
using PIC = DocumentFormat.OpenXml.Drawing.Pictures;
namespace Wisdombud.Office
{
public static class OpenXmlUtil
{
///
/// 按书签替换图片
///
///
///
///
/// 宽度厘米
/// 高度厘米
///
public static void ReplaceBMPicture(string filePath, string picPath, string bm)
{
RemoveBookMarkContent(filePath, bm);
InsertBMPicture(filePath, picPath, bm);
}
///
/// 按书签替换图片
///
///
///
///
/// 宽度厘米
/// 高度厘米
///
public static void ReplaceBMPicture(string filePath, string picPath, string bm, long x, ImagePartType type)
{
RemoveBookMarkContent(filePath, bm);
InsertBMPicture(filePath, picPath, bm, x, type);
}
///
/// 按书签替换图片
///
///
///
///
/// 宽度厘米
/// 高度厘米
///
public static void ReplaceBMPicture(string filePath, string picPath, string bm, long x, long y, ImagePartType type)
{
RemoveBookMarkContent(filePath, bm);
InsertBMPicture(filePath, picPath, bm, x, y, type);
}
///
/// 按书签插入图片
///
///
///
///
/// 宽度厘米
/// 高度厘米
///
public static void InsertBMPicture(string filePath, string picPath, string bm, long x, ImagePartType type)
{
long y = 0;
using (System.Drawing.Bitmap objPic = new System.Drawing.Bitmap(picPath))
{
y = (x * objPic.Height) / objPic.Width;
}
Inser
















