【官网API】
pom
<!-- 自动依赖org.apache.poi -->
<dependency>
<groupId>com.deepoove</groupId>
<artifactId>poi-tl</artifactId>
<version>1.10.0</version>
</dependency>
word模板
模板内容
{{?list}}
{{tableName}}表
{{tables}}数据项英文名称 | 数据项中文名称 | 数据类型 | 类型长度 | 说明 |
---|---|---|---|---|
[fieldOfEn] | [fieldOfCn] | [fieldType] | [fieldLength] |
{{/list}}
代码实现
ExcelBean
import lombok.Data;
/**
* @FileName: ExcelBean
* @Description: 从Excel读取数据
*/
@Data
public class ExcelBean {
@ExcelProperty("表名")
private String tableName;
@ExcelProperty("字段英文名称")
private String fieldOfEn;
@ExcelProperty("字段中文名称")
private String fieldOfCn;
@ExcelProperty("字段类型")
private String fieldType;
@ExcelProperty("类型长度")
private String fieldLength;
}
Test Method
读取excel数据,进行转化写入word
public void test_Lord(){
String path = "D:\\xuanji_dwd/资产.xlsx";
templateParse(path);
}
public void templateParse(String dataStandardExcelPath) {
try (FileInputStream fileInputStream = new FileInputStream(dataStandardExcelPath)) {
ZipSecureFile.setMinInflateRatio(0.001);
List<ExcelBean> fields = EasyExcel.read(fileInputStream, ExcelBean.class, null).doReadAllSync();
Map<String, List<ExcelBean>> groupMap = fields.stream().collect(Collectors.groupingBy(ExcelBean::getTableName));
List<Map<String,Object>> foreachList = new ArrayList<>();
groupMap.forEach((String tableName,List<ExcelBean> beans)->{
Map<String,Object> map = new HashMap<>();
map.put("tables",beans);
map.put("tableName",tableName);
foreachList.add(map);
});
Map<String,Object> resMap = new HashMap<>();
resMap.put("list",foreachList);
// 破解循环表格
LoopRowTableRenderPolicy policy = new LoopRowTableRenderPolicy();
Configure config = Configure.builder()
.bind("tables", policy)
.build();
XWPFTemplate.compile(new File("D:\\docx/template.docx"),config).render(resMap).writeAndClose(new FileOutputStream("D:\\docx/output.docx"));
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}