Java将对象信息写到word模板中
一.首先进行依赖的导入
<!-- 证书模板写入信息 -->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.10.0</version>
</dependency>
二.配置word模板
说明:
对象文字属性,用模板括号{{}}标记
对象中头像属性用{{@}} 标记
三.Java代码编写
此处new了一个map用来存储要写入对象中的信息
//操作word文档
try {
HashMap<String, Object> map = new HashMap<>();
map.put("CERT_NAME",cert.getTitle());
map.put("REAL_NAME",user.getRealName());
map.put("ID_CARD",user.getIdCard());
map.put("CERT_NO",cert.getId());
map.put("AUTHORITY",cert.getAuthority());
map.put("START_TIME",sdf.format(new Date()));
map.put("END_TIME",date);
// map.put("AVATAR_IMG")
PictureRenderData pictureRenderData = Pictures.ofStream(new FileInputStream(realPathPicture), PictureType.PNG)
.size(102,126).create();
map.put("AVATAR",pictureRenderData);
url = uploadCert(grant,cert.getTmpl(), map);//该方法中调用了下方函数 repalceTemplate()
grant.setCertFileOrig(url);
}catch (Exception e){
e.printStackTrace();
throw new ServiceException("证书授予失败,请联系管理员");
}
//将word模板填充信息
public static void replaceTemplate(String templateFilePath,String resultFilePath,Map<String,Object> map){
try {
//此处一行代码即可以操作word将map信息写入
//此处templateFilePath表示模板位置,resultFilePath 表示写入后的word存储位置,map表示上面的对象信息
XWPFTemplate.compile(templateFilePath).render(map).writeToFile(resultFilePath);
} catch (Exception e) {
e.printStackTrace();
}
}