实现java 替换 word中指定内容,实现word2003 版本 很轻松的 完成了,可是到2007版本时缺头疼了。因为在网上查找的很多相关例子都是需要删除哪一行的信息在setText 添加进去这样不是我所想要的,本人所想要的是可以像 2003那样 直接replace 替换。

word 2007 实现原理是 2007版本可以通过解压、压缩的方式获取到word的xml文件,通过xml文件读成String然后用replace方法来完成。

2003 word 替换代码:

FileInputStream in = new FileInputStream(new File(file));
HWPFDocument hdt = new HWPFDocument(in);
// 读取word文本内容
Range range = hdt.getRange();
// 替换文本内容
for (Map.Entry<String, String> entry : map.entrySet()) {
range.replaceText(entry.getKey(), entry.getValue());
}
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
FileOutputStream out = new FileOutputStream(newFile.replace(".docx", ".doc"), true);
hdt.write(ostream);
// 输出字节流
out.write(ostream.toByteArray());
out.close();
ostream.close();
System.out.println("2003-word-只可以导出2003版本...");
System.out.println("2003-word-Success...");

word 2007 实现代码:

String WordName=newFile.split("/")[newFile.split("/").length-1];//word is name
String SaveURL=newFile.replace(WordName, "");
/**解压word**/
File file1 = new File(file);// 取得word文件
String dir = SaveURL+"\\zipFile\\";// 取得要解压缩文件到的目录
FileInputStream inputStream = new FileInputStream(file1);
ZipInputStream zipInputStream = new ZipInputStream(inputStream);
ZipEntry entry = null;
byte ch[] = new byte[256];
while ((entry = zipInputStream.getNextEntry()) != null) {
File zFile = new File(dir + entry.getName());
if (entry.isDirectory()) {
if (!zFile.exists()) {
zFile.mkdirs();
}
zipInputStream.closeEntry();
} else {
File fpath = new File(zFile.getParent());
if (!fpath.exists()) {
fpath.mkdirs();
}
FileOutputStream outputStream = new FileOutputStream(zFile);
int i;
while ((i = zipInputStream.read(ch)) != -1) {
outputStream.write(ch, 0, i);
}
zipInputStream.closeEntry();
outputStream.close();
}
}
inputStream.close();
System.out.println("word解压成功...");
/**替换内容**/
String documentXMLUrl=SaveURL+"\\zipFile\\word\\document.xml";
SAXReader reader = new SAXReader();
Document document= reader.read(documentXMLUrl);
Element _root = document.getRootElement();
String xml=_root.asXML();
for (Map.Entry<String, String> _entry : map.entrySet()) {
xml=xml.replace(_entry.getKey(), _entry.getValue());
}
document = reader.read(new ByteArrayInputStream(xml.getBytes()));
XMLWriter writer=null;
writer = new XMLWriter(new FileWriter(documentXMLUrl));
writer.write(document);
writer.close();
System.out.println("word替换成功...");
/**压缩成word**/
ZipOutputStream zipOutputStream = new ZipOutputStream(
new FileOutputStream(new File(newFile))); // 要压缩文件的路径及名称
String root = SaveURL + "\\zipFile\\";
String current = SaveURL + "\\zipFile\\";
File rootFile = new File(root);
File currentFile = new File(current);
addAllFiles(zipOutputStream, rootFile, currentFile);
zipOutputStream.close();
System.out.println("word压缩成功...");

全部代码:

package com.freemarker;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.zip.ZipEntry;
import java.util.zip.ZipInputStream;
import java.util.zip.ZipOutputStream;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;
public class VolumeProductionWord {
public void WordReplace(String file, String newFile, Map<String, String> map)
throws IOException, DocumentException {
try {
FileInputStream in = new FileInputStream(new File(file));
HWPFDocument hdt = new HWPFDocument(in);
// 读取word文本内容
Range range = hdt.getRange();
// 替换文本内容
for (Map.Entry<String, String> entry : map.entrySet()) {
range.replaceText(entry.getKey(), entry.getValue());
}
ByteArrayOutputStream ostream = new ByteArrayOutputStream();
FileOutputStream out = new FileOutputStream(newFile.replace(".docx", ".doc"), true);
hdt.write(ostream);
// 输出字节流
out.write(ostream.toByteArray());
out.close();
ostream.close();
System.out.println("2003-word-只可以导出2003版本...");
System.out.println("2003-word-Success...");
} catch (Exception ex) {
String WordName=newFile.split("/")[newFile.split("/").length-1];//word is name
String SaveURL=newFile.replace(WordName, "");
/**解压word**/
File file1 = new File(file);// 取得word文件
String dir = SaveURL+"\\zipFile\\";// 取得要解压缩文件到的目录
FileInputStream inputStream = new FileInputStream(file1);
ZipInputStream zipInputStream = new ZipInputStream(inputStream);
ZipEntry entry = null;
byte ch[] = new byte[256];
while ((entry = zipInputStream.getNextEntry()) != null) {
File zFile = new File(dir + entry.getName());
if (entry.isDirectory()) {
if (!zFile.exists()) {
zFile.mkdirs();
}
zipInputStream.closeEntry();
} else {
File fpath = new File(zFile.getParent());
if (!fpath.exists()) {
fpath.mkdirs();
}
FileOutputStream outputStream = new FileOutputStream(zFile);
int i;
while ((i = zipInputStream.read(ch)) != -1) {
outputStream.write(ch, 0, i);
}
zipInputStream.closeEntry();
outputStream.close();
}
}
inputStream.close();
System.out.println("word解压成功...");
/**替换内容**/
String documentXMLUrl=SaveURL+"\\zipFile\\word\\document.xml";
SAXReader reader = new SAXReader();
Document document= reader.read(documentXMLUrl);
Element _root = document.getRootElement();
String xml=_root.asXML();
for (Map.Entry<String, String> _entry : map.entrySet()) {
xml=xml.replace(_entry.getKey(), _entry.getValue());
}
document = reader.read(new ByteArrayInputStream(xml.getBytes()));
XMLWriter writer=null;
writer = new XMLWriter(new FileWriter(documentXMLUrl));
writer.write(document);
writer.close();
System.out.println("word替换成功...");
/**压缩成word**/
ZipOutputStream zipOutputStream = new ZipOutputStream(
new FileOutputStream(new File(newFile))); // 要压缩文件的路径及名称
String root = SaveURL + "\\zipFile\\";
String current = SaveURL + "\\zipFile\\";
File rootFile = new File(root);
File currentFile = new File(current);
addAllFiles(zipOutputStream, rootFile, currentFile);
zipOutputStream.close();
System.out.println("word压缩成功...");
/**删除解压word相关文件**/
if(deleteDirectory(root)){
System.out.println("成功删除多余文件...");
}else{
System.out.println("删除多余文件失败...");
}
System.out.println("2007-word-Success...");
}
}
/**压缩文件**/
private void addAllFiles(ZipOutputStream zipOutputStream, File current,
File root) throws IOException {
byte buffer[] = new byte[4096];
int bytesIndex;
String entries[] = current.list();
for (int i = 0; i < entries.length; i++) {
File f = new File(current, entries[i]);
if (f.isDirectory()) {
addAllFiles(zipOutputStream, f, root);
continue;
}
String relativePath = getRelativePath(current, root);
FileInputStream fileInputStream = new FileInputStream(f);
if (!relativePath.equals("")) {
relativePath = relativePath + "/";
}
ZipEntry entry = new ZipEntry(relativePath + f.getName());
zipOutputStream.putNextEntry(entry);
while ((bytesIndex = fileInputStream.read(buffer)) != -1) {
zipOutputStream.write(buffer, 0, bytesIndex);
}
fileInputStream.close();
}
}
/**获取相对路径**/
private static String getRelativePath(File currentFile, File rootFile) {
int len = rootFile.getPath().length();
String rePath = currentFile.getPath().substring(len);
if (rePath.length() > 0) {
rePath = rePath.substring(1);
}
return rePath;
}
/**
* 删除目录(文件夹)以及目录下的文件
* @param   sPath 被删除目录的文件路径
* @return  目录删除成功返回true,否则返回false
*/
public boolean deleteDirectory(String sPath) {
//如果sPath不以文件分隔符结尾,自动添加文件分隔符
if (!sPath.endsWith(File.separator)) {
sPath = sPath + File.separator;
}
File dirFile = new File(sPath);
//如果dir对应的文件不存在,或者不是一个目录,则退出
if (!dirFile.exists() || !dirFile.isDirectory()) {
return false;
}
boolean flag = true;
//删除文件夹下的所有文件(包括子目录)
File[] files = dirFile.listFiles();
for (int i = 0; i < files.length; i++) {
//删除子文件
if (files[i].isFile()) {
flag = deleteFile(files[i].getAbsolutePath());
if (!flag) break;
} //删除子目录
else {
flag = deleteDirectory(files[i].getAbsolutePath());
if (!flag) break;
}
}
if (!flag) return false;
//删除当前目录
if (dirFile.delete()) {
return true;
} else {
return false;
}
}
/**
* 删除单个文件
* @param   sPath    被删除文件的文件名
* @return 单个文件删除成功返回true,否则返回false
*/
public boolean deleteFile(String sPath) {
boolean flag = false;
File file = new File(sPath);
// 路径为文件且不为空则进行删除
if (file.isFile() && file.exists()) {
file.delete();
flag = true;
}
return flag;
}
/**
* @param args
* @throws DocumentException
*/
public static void main(String[] args) throws DocumentException {
// TODO Auto-generated method stub
Map<String, String> map = new HashMap<String, String>();
map.put("$name", "测试名称");
map.put("$age", "测试年龄");
map.put("$weight", "72kg");
map.put("$maritalStatus", "否");
map.put("$IndividualResume", "这里是个人简历!");
VolumeProductionWord word = new VolumeProductionWord();
try {
word.WordReplace("WordUploading/1FreeMarker.docx",
"FormWork/FreeMarker3.docx", map);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}

源代码:http://down.51cto.com/data/817801

转载于:https://blog.51cto.com/brucezhang51/1213770

java poi操作word 2003 2007相关推荐

  1. java poi 操作word遇到的问题

    java poi 操作word文本,图表,遇到的问题 直接上问题 模板字段匹配问题 图表问题 图表导出 问题:模板找不到对应图表 问题:数据填充后效果不达目标 图表中为零的数值去掉(!!!模板层面解决 ...

  2. poi操作word 2003/doc

    poi操作word 2003/doc HWPFDocument中的要素 maven引用 通过WordExtractor读取文本 通过HWPFDocument读文件 通过HWPFDocument写文件 ...

  3. java poi读取word 2003, 2007文档

    前言 最近本来想写linux的 但是工作太忙一直腾不出手学习. 所以我打算最近出: 1.shiro 一个权限模块定制化很强的安全框架. 2. elasticSearch 全文检索, 分词分片. 3. ...

  4. java poi操作word模版 导出word文档(附工具类)

    模板格式 合同编号:{ contractNumber},合同序号:{ contractSequence} 买家: { buyerName} 卖家:{ sellerName} 业务员: { salesN ...

  5. Java poi 操作word替换模版中固定参数(页眉、段落、表格)

    近期碰到一个稍微头疼的需求,将word模版中的参数替换为实际值,其中包括段落.列表(行数不够时自动递增).页眉:本文以docx文档为例,其中代码有其他地方参考,如有冒犯,还请海涵: 模版: 实现效果: ...

  6. java word apache poi 操作word模板。

    apache poi 操作word模板. 操作方式: 1.对于固定格,可以遍历格子然后替换其中指定的值例如在要替换的cell写入${example} 这样格式,遍历到之后替换. 2.对于需要增长的表格 ...

  7. 【JAVA - POI 合集】之 POI 操作word 图表,柱状图,折线图,雷达图,条形图 poi4.1.2

    1.前言 关于poi 操作word 的吐槽: 山路崎岖, 一言难尽啊!!! 原本项目中的poi 版本是3.17的版本,但是3.17对于在word 中操作图表是有问题的.所以对项目的jar 包进行了升级 ...

  8. java使用poi操作word模板,插入图片、段落、表格

    java使用poi操作word插入图片.段落.表格 其他链接 准备工作 创建word模板.docx文件 编写模板格式.xml文件 java上手poi maven依赖 使用到的包 具体应用 对应封装方法 ...

  9. POI操作Word设置表格在字体加粗【XWPFTableCell设置字体】Java操作Word调样式

    Jar包的版本号:[不同的版本号也许也可以,可以尝试一下,哈哈哈哈~] ----------因为代码在内网环境中无法复制出来,所以这里就截图了,兄弟们自己敲一下键盘吧~ POI操作Word设置表格在字 ...

最新文章

  1. epoch如何设置_使用TFRecordDataset时如何设置epoch计数器?
  2. 入职大厂,我容易吗?
  3. SPI、UART、I2C三种串行总线简介
  4. 单向链表 双向链表 java代码实现
  5. IOS中NSUserDefaults的用法(轻量级本地数据存储)
  6. mkdir用大括号同时建立多个同级和下级目录
  7. winform窗体最大化、最小化、还原
  8. Mysql修改字段长度
  9. 西南科技大计算机实验室,西南科技大学|关于公布西南科技大学本科教学实验室建制的通知|...
  10. 用PHP实现小写金额转换大写金额【精确到分】
  11. 2020 05 02 记录思考
  12. 闲聊机器人实例三:python实现小姜机器人(检索式chatbot_sentence_vec_by_word_词向量句向量)
  13. 阿里云云计算工程师ACA认证(Alibaba Cloud Certified Associate - Cloud Computing)考试大纲-V3.0
  14. [书籍分享]0-009.微信营销与运营解密:利用微信创造商业价值的奥秘
  15. 京东单品页前端开发那些不得不说的事儿
  16. 服务器2003共享文件夹,2003服务器共享文件夹
  17. 20岁后长高增高秘诀
  18. MongoDB未授权访问漏洞
  19. 一个列子演示java中弱引用的回收时机
  20. 005_解密饿了么大前端团队

热门文章

  1. ZeroMQ的一些配置
  2. centos7.9使用jenkins部署springcloud微服务_配合SVN_脚本_实现自动部署后端以及前端程序_亲测成功---持续集成部署Jenkins工作笔记0023
  3. 微服务升级_SpringCloud Alibaba工作笔记0011---Gateway常用的predicate
  4. STM32工作笔记0055---认识pcbdoc文件Schdoc文件
  5. C#.Net工作笔记018---葡萄城控件FlexGrid自定义单元格_以及给自定义控件添加自定义事件
  6. security工作笔记004---.NET Web安全性-身份验证和授权(一)之Principal
  7. 2013浙大878计算机基础综合大题答案解析
  8. 疫苗:Java HashMap的死循环(转)
  9. echarts中国地图描绘
  10. 随想录(cloud 网络库)