- 建议使用hutool工具类来实现,maven依赖。
<dependency>
<groupId>cn.hutool</groupId>
<artifactId>hutool-all</artifactId>
<version>5.2.4</version>
</dependency>
- 使用方式demo,这里面使用了hutool工具类的自动换行和设置列值的方法可以让你少写很多很多代码
public static void main(String[] args) throws IOException {
collapseRow();
}
private static void collapseRow() throws IOException {
try (SXSSFWorkbook workbook = new SXSSFWorkbook(100)) {
SXSSFSheet sheet = workbook.createSheet("new sheet");
//提前创建好样式,如果你在for循环内设置样式的话,样式对象是有限的会导致有些样式缺失但不报错的问题。一定要注意!!!!
StyleSet styleSet = new StyleSet(workbook);
//设置边框和边款颜色
styleSet.setBorder(BorderStyle.THIN, IndexedColors.PINK);
//单元格内容自动换行
styleSet.setWrapText();
ArrayList<String> titleList = CollUtil.newArrayList("编号", "创建时间", "数量", "是否正确", "详细内容", "名称");
int lastRowNum = 0;
Row row = RowUtil.getOrCreateRow(sheet, lastRowNum++);
//设置表格
int cellNum = 0;
for (String titleName : titleList) {
//设置单元格内容的时候直接将样式代入就可以了
CellUtil.setCellValue(row.createCell(cellNum++), titleName, styleSet.getHeadCellStyle());
}
List<Map<String, Object>> dataList = new ArrayList<>();
Map<String, Object> resultMap = new LinkedHashMap<>();
resultMap.put("code", "C01");
resultMap.put("createTime", LocalDate.now());
resultMap.put("qty", 2000);
resultMap.put("isStop", true);
resultMap.put("id", "窗前明月光,疑似地上霜。举头望明月,低头思故乡。");
resultMap.put("name", "哒哒");
dataList.add(resultMap);
resultMap = new LinkedHashMap<>();
resultMap.put("code", "C02");
resultMap.put("createTime", LocalDate.now());
resultMap.put("qty", 20000);
resultMap.put("isStop", false);
resultMap.put("id", "日照香炉生紫烟,遥看瀑布挂前川。飞流直下三千尺,疑是银河落九天。");
resultMap.put("name", "滴滴");
dataList.add(resultMap);
//填充数据
for (Map<String, Object> map : dataList) {
row = RowUtil.getOrCreateRow(sheet, lastRowNum++);
cellNum = 0;
for (String key : map.keySet()) {
Object value = map.get(key);
Cell cell = CellUtil.getOrCreateCell(row, cellNum++);
//设置单元格内容的时候直接将样式代入就可以了
CellUtil.setCellValue(cell, value, styleSet, false);
}
}
try (FileOutputStream fileOut = new FileOutputStream("gideonYeung.xlsx")) {
workbook.write(fileOut);
log.error("导出成功。");
} finally {
workbook.dispose();
}
}
}
- 导出的结果。
解决POI导出Excel单元格内容换行问题