实现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