本文以解决问题为主,就不对Apache POI做过多解释,感兴趣可自行搜索。如果不介意使用xml作为模板文件生成word文档,推荐使用freemark,但是生成的word上传后可能会出现格式问题不支持预览,因为freemark生成的word实质上还是xml格式,预览的时候是xml文件(不兼容openoffice或liboffice),正是为解决此问题,使用Apache POI生成word。
1.pom.xml
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi</artifactId>
<version>3.17</version>
</dependency>
<dependency>
<groupId>org.apache.poi</groupId>
<artifactId>poi-scratchpad</artifactId>
<version>3.17</version>
</dependency>
2.创建目标模板文件,命名为template.doc,放置在resource/templates/template.doc
用${}来标记要替换的字段,例如${createTime}是将createTime替换成真实的创建时间
3.数据模型,包含具体数据的map对象
由于我这里是导出聊天记录,所以会需要进行格式处理,去掉文本中的html标签和防止字符转义,
String str = StringEscapeUtils.unescapeHtml(jsonObject.getString("payload").replaceAll("</?[^>]+>", ""));
这一句是为了拼接会议内容,由于会议内容是list数组,而模板只有一个${chatRecordList}用来替换,所以需要先将数据拼接好。格式:序号、姓名:聊天内容
我还在后面拼了一个${newline},这个拼接内容命名看个人喜欢,目的是为了后面替换为换行。
String record = i+"、"+messageList.get(i).getSenderName()+"