一、添加pom依赖:
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-base</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-web</artifactId>
<version>4.1.2</version>
</dependency>
<dependency>
<groupId>cn.afterturn</groupId>
<artifactId>easypoi-annotation</artifactId>
<version>4.1.2</version>
</dependency>
二、excel模板如图:
三、将数据填充为map,调用导出方法
Map<String, Object> data = new HashMap<String, Object>(3);
data.put("content", sb.toString());
data.put("indexNames", indexNames);
Map<String, Object> maps = new HashMap<String, Object>(2);
maps.put("indexManage", data);
File file = new File(filePath);
if (!file.exists()) {
// 路径不存在
file.mkdirs();
}
ExcelOutUtil.exportIndexToDirectByTemp(indexNames.size(), maps, "file/指标生成模板.xlsx", formulaIdIn.getFormulaInfoId() + "指标模板.xlsx", new Integer[]{1}, filePath);
四、exportIndexToDirectByTemp具体内容为:
public static void exportIndexToDirectByTemp(Integer indexSize,Map<String, Object> param, String path, String fileName, Integer[] sheetNums, String direct) {
OutputStream out = null;
try {
TemplateExportParams params = new TemplateExportParams(path, true);
//要使用横向遍历必须设置为true
params.setColForEach(true);
params.setStyle(ExcelStyleType.BORDER.getClazz());
//params.setSheetNum(new Integer[]{1, 2, 3, 4});
params.setSheetNum(sheetNums);
Workbook book = ExcelExportUtil.exportExcel(params, param);
setCell(book,indexSize,0);
setCell(book,indexSize,1);
exportToDirect(direct, book, fileName);
} catch (Exception e) {
throw new RuntimeException("导出异常", e);
}
}
//设置边框样式并合并单元格
public static void setCell(Workbook book,Integer indexSize,Integer rowNum){
//CellRangeAddress(第几行开始,第几行结束,第几列开始,第几列结束)
CellRangeAddress craOne = new CellRangeAddress(rowNum, rowNum, 0, indexSize+1);
Sheet sheet = book.getSheetAt(0);
sheet.addMergedRegion(craOne);
Row row = sheet.getRow(rowNum);
CellStyle style = book.createCellStyle();
// 设置边框样式
style.setBorderTop(BorderStyle.THIN);
style.setBorderBottom(BorderStyle.THIN);
style.setBorderLeft(BorderStyle.THIN);
style.setBorderRight(BorderStyle.THIN);
for (int i = 1; i <= indexSize+1; i++) {
Cell cell = row.getCell(i);
if (cell == null) {
cell = row.createCell(i);
}
cell.setCellStyle(style);
}
}
五、最终导出结果: