通过POI类库实现word文档的创建。
思路:
通过自定义变量名,利用替换的方式,将所需数据填入,一般用于生成固定格式的报告。如果需要填入的数据很多,则略繁琐。
注意:
a)、例子中给的只能替换变量,不能根据结果生成多行数据。例如表格等。
b)、目前支持DOC格式,不支持DOCX格式。
1、需要新建一个word模版,在需要输入数据的地方填入:
${变量名}
变量名称根据自行需要更改。不可有重复名称。
2、通过POI类,进行变量的替换,以实现word文件的生成。
3、示例:
public static void CreatWordByModel(String tmpFile, Map<String, String> contentMap, String exportFile) throws Exception{
InputStream in = null;
in = new FileInputStream(new File(tmpFile));
HWPFDocument document = null;
document = new HWPFDocument(in);
// 读取文本内容
Range bodyRange = document.getRange();
System.out.println(bodyRange.toString());
System.out.println(bodyRange.text());
// 替换内容
for (Map.Entry<String, String> entry : contentMap.entrySet()) {
bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());
}
//导出到文件
try {
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
document.write((OutputStream)byteArrayOutputStream);
OutputStream outputStream = new FileOutputStream(exportFile);
outputStream.write(byteArrayOutputStream.toByteArray());
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
}
public static void main(String[] args) throws Exception {
Map map=new HashMap();
map.put("data1","20190301");
map.put("data2","你好");
map.put("data3","这是一个测试");
map.put("data4","CSDN");
map.put("data5","https://blog.csdn.net/yxf771hotmail");
CreatWordByModel("C:/model.doc",map,"C:/newfile.doc");
}
4、结果:
模版:
结果:
打赏