demo地址:https://gitee.com/ohaha123/poi_hwpf_demo
一,引入mavn
按照下面的依赖实测可以,不然会有各种问题,找不到类 找不到方法的都错误都出现过。
<poi.version>4.1.2</poi.version>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>${poi.version}</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-ooxml</artifactId>
<version>${poi.version}</version>
</dependency>
二、编写代码
下面的方法会替换模版文件,而不会丢下你原来的格式,比如模版中是有下划线的 ,替换后还保留下划线,网上找了好多例子样式都是奇奇怪怪的。试了多次之后只有下面的方法能到达预期的效果。
replaceDoc方法
/**
*
* @param inUrl 模版文件路径
* @param outUrl 输出文件路径
* @param params 参数
* @throws Exception
*/
public static void replaceDoc(String inUrl,String outUrl,Map<String,String> params) throws Exception {
FileInputStream in1 = new FileInputStream(inUrl);
HWPFDocument doc = new HWPFDocument(in1);
Range range = doc.getRange();
for (Map.Entry<String,String> entry:
params.entrySet()) {
range.replaceText(entry.getKey(), entry.getValue());
}
// 另存模板文件为exportTestg.doc
FileOutputStream out = new FileOutputStream(outUrl);
doc.write(out);
out.flush();
out.close();
}
三、看看效果
文档模版:
生成的文档效果