记得之前整理过这easyPoi的使用方法,但是今天找的时候没找到,只能自己再整理更一篇博客了。😔
因为需求是很简单的根据word模板导出,没涉及到图片什么的,所以特地准备了官方文档供小伙伴们查看。easyPoi官方文档
maven项目可以直接通过pom文件引入依赖
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>3.2.0</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>3.2.0</version>
</dependency>
非maven项目可以通过classpath引入jar文件,官网上的jar包下载链接无法访问,只能使用的时候自己找一下咯。🤗
模板展示,只需要将你要动态改变的参数设置一下就好啦
java代码
@GetMapping("/provinceApprovalCertificateSucc")
public AjaxResult provinceApprovalCertificateSucc(@RequestParam("casr_id") Integer casr_id,
@RequestParam("stuId") Integer stuId) throws ParseException {
CertApplyStuRelevance certApplyStuRelevance = certApplyStuRelevanceMapper.selectById(casr_id);
Integer cert_apply_stu_id = certApplyStuRelevance.getCertApplyStuId();
// 证书申报学员信息
CertApplyStu certApplyStu = certApplyStuMapper.selectById(cert_apply_stu_id);
Map<String, Object> map = new HashMap<String, Object>();
map.put("reportDeptName", certApplyStuRelevance.getReportDeptName());
map.put("reportTime", DateUtils.CSTDateToFormatStr(certApplyStuRelevance.getReportTime().toString()));
map.put("nowDay", DateUtils.CSTDateToFormatStr(DateUtils.getNowDate().toString()));
map.put("computerNumber", certApplyStu.getComputerNumber());
map.put("nowDate", DateUtils.CSTDateToFormatStr(DateUtils.getNowDate().toString()));
TrainClassStudent trainClassStudent = trainClassStudentMapper.selectById(stuId);
if (trainClassStudent == null) {
return AjaxResult.error("学员信息不存在");
}
// 获取模板路径
String templatePath =
GlConfig.getTemplatePath() + "suc.docx";
String fileName = stuId + trainClassStudent.getName() + ".docx";
String savePath = GlConfig.getUploadPath() + "/certificate/succcess/" + fileName;
// 创建word文档
ExportWordUtils.generateWord(templatePath, map, savePath);
// 更新学生信息
trainClassStudent.setWritUrl("/upload/certificate/success/" + fileName);
return AjaxResult.success(trainClassStudentMapper.updateById(trainClassStudent));
}
/**
* 生成word文件
*
* @param templatePath
* @param map
*/
public static void generateWord(String templatePath, Map<String, Object> map, String savePath) {
try {
// 保存word文件的文件夹如果不存在话创建文件夹
File file = FileUtil.file(savePath);
if (!file.exists()) {
file.getParentFile().mkdirs();
}
// 使用easypoi生成word文档 不过好像是只支持07版本
XWPFDocument doc = WordExportUtil.exportWord07(
templatePath, map);
FileOutputStream fos = new FileOutputStream(savePath);
doc.write(fos);
fos.close();
} catch (Exception e) {
e.printStackTrace();
}
}