java openxml 操作 word_OpenXML操作word

本文介绍了使用OpenXML SDK替代COM接口操作Word的优势,包括稳定性、速度和跨平台支持。OpenXML SDK提供了一个Productivity Tool工具,便于理解和操作Word文档。通过代码示例展示了如何按书签插入和替换图片,修改书签内容以及删除、重命名和合并文档等功能。
摘要由CSDN通过智能技术生成

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的基本结构。

1d7ae762e25e2d9466336e5053265aa6.png

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;

}

Insert

  • 1
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值