Java web项目用模板填充方式生成word文档
最近在项目开发中遇到根据规则生成word文档的需求,以前利用Framework生成flt模板之后填充进行word文档生成,但生成flt对格式校验要求较高 ,所以尝试用poi-tl工具生成,发现应用代码简洁高效,话不多说,直接上代码。
一、运行效果
二、使用步骤
1.pom.xml依赖
<!-- word start -->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.10.5</version>
</dependency>
<!-- word end -->
<!-- Slf4j日志包,可以不用 -->
<dependency>
<groupId>org.projectlombok</groupId>
<artifactId>lombok</artifactId>
<version>1.18.18</version>
<scope>provided</scope>
</dependency>
2.word生成工具类
WordTemplateUtils.java代码如下:
import com.deepoove.poi.XWPFTemplate;
import lombok.extern.slf4j.Slf4j;
import org.springframework.util.StringUtils;
import java.io.File;
import java.util.Map;
/**
* 根据参数填充word模板生成word文档工具
*/
@Slf4j
public class WordTemplateUtils {
/**
*
* @param templatePath 模板文件地址
* @param filePath 生成word文件地址
* @param map 模板填充参数
* @return
*/
public static boolean compileWordTemplate(String templatePath, String filePath,Map<String, Object> map){
// 在实际项目应用中返回可自行修改, RestResponse<Map<String, String>>
try {
// templatePath和filePath不能为空,可自行判空
/*if(StringUtils.isEmpty(templatePath)){
log.info("模板文件不能为空!!!");
return false;
}
if(StringUtils.isEmpty(filePath)){
log.info("生成word文件地址不能为空!!!");
return false;
}*/
if(map == null){
log.info("入参参数不能为空!!!");
return false;
}
File file = new File(filePath);
// 判断上级目录是否存在,不存在创建目录
if(!file.getParentFile().exists()){
file.getParentFile().mkdirs();
}
XWPFTemplate.compile(templatePath).render(map).writeToFile(filePath);
return true;
}catch (Exception e){
e.printStackTrace();
log.info("word文档生成失败!!!");
return false;
}
}
}
3.测试类
WordTemplateTest.java代码如下:
import java.util.HashMap;
import java.util.Map;
public class WordTemplateTest {
public static void main(String[] args) {
// 模板文件路径
String templatePath = "D:\\project_demo\\jrtyEntrustWord.docx";
// 生成文件路径
String filePath = "D:\\project_demo\\投后核息确认函.docx";
// 组装参数
Map<String, Object> map = new HashMap<>();
map.put("productName","2024年第二期住房抵押贷款资产支持证券");
map.put("busiDate","2024年01月29日");
map.put("busiName","2024年第二期住房抵押贷款/2089147.IB");
map.put("busiAmt","100,000,000.00");
map.put("rate","5.70%");
map.put("interestAccrual","365");
map.put("interestDays","31");
map.put("regularRate","浮动");
map.put("adjustDesc","下一计息期间基准利率为2024年12月5年期以上LPR,即7.30%,基本利差为-1.60%,利率为5.70%");
map.put("rateCycle","2023/1/26-2024/1/26");
map.put("interestBegin","2023-12-26");
map.put("interestEnd","2024-01-26");
map.put("investAmt","48,787,200.00");
map.put("residueAmt","47,464,000.00");
map.put("accruedInterest","108,842.10");
map.put("principalInterestSum","48,896,042.10");
map.put("year","2024");
map.put("month","01");
// 方法调用
WordTemplateUtils.compileWordTemplate(templatePath,filePath,map);
}
}