批量替换word中的字符,请注意这个替换不是很完整,存在无法完全替换的情况。
package test.java;
import java.io.File;
import java.util.ArrayList;
import java.util.List;
import com.spire.doc.Document;
import com.spire.doc.FileFormat;
public class WordReplace {
List<String> filelist = new ArrayList<String>();
public List<String> getFile(File file) {
if (file != null) {
File[] f = file.listFiles();
if (f != null) {
for (int i = 0; i < f.length; i++) {
getFile(f[i]);
}
} else {
filelist.add(file.getAbsolutePath());
}
}
return filelist;
}
public static void main(String[] args) {
// TODO Auto-generated method stub
WordReplace wr = new WordReplace();
File file = new File("F:\\miscellaneous\\test");
for (String filepath : wr.getFile(file)) {
filepath = filepath.trim();
if (filepath.endsWith("docx") || filepath.endsWith("doc")) {
System.out.println(filepath);
// 加载Word文档
Document document = new Document(filepath);
// 使用新文本替换文档中的指定文本
document.replace("四川省", "四川", false, true);
String realpath = filepath;
if (filepath.endsWith("docx")) {
// 保存文档
document.saveToFile(realpath, FileFormat.Docx_2013);
} else {
// 保存文档
document.saveToFile(realpath, FileFormat.Doc);
}
}
}
}
}