1 效果演示
效果演示截图
2 实现过程
2.1 导入jar包
org.apache.poi
poi
3.17
org.apache.poi
poi-scratchpad
3.17
2.2 实现代码
不啰嗦,直接上代码。
package WordTest;
import org.apache.poi.hwpf.HWPFDocument;
import org.apache.poi.hwpf.usermodel.Range;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.io.OutputStream;
public class WordDemoUtils {
public static void main(String[] args) {
replaceWordKeyWord();
}
public static void replaceWordKeyWord() {
try {
String serverPath = "E:\\TEST\\tmpl2.doc";
InputStream is = new FileInputStream(serverPath);
HWPFDocument doc = new HWPFDocument(is);
Range range = doc.getRange();
range.replaceText("${year}", "2020");
range.replaceText("${morning}", "早上");
OutputStream os = new FileOutputStream("E:\\TEST\\target.doc");
//把doc输出到输出流中
doc.write(os);
is.close();
os.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}
自测过程中发现的小问题及解决方法:
原本最初我使用的模板后缀为.docx,可自测过程中报了如下错误:java.lang.IllegalArgumentException: The document is really a OOXML file。
解决方法:我将docx的文件另存为低版本的doc文件,即解决上述了问题。
所以这里做个小总结,模板和输出文件都要是doc文件。