Java 利用hutool工具实现导出excel并合并单元格
多个合并 就继续分组即可
多个效果
public AjaxJson exportFileDriver(AtNewOrder atNewOrder, HttpServletRequest request, HttpServletResponse response) throws IOException {
List<OrderExportVo> orderExportVos = atNewOrderService.orderDriverList(atNewOrder);
ExcelWriter writer = ExcelUtil.getBigWriter();
if (1==1){
List<String> rowHead = CollUtil.newArrayList("司机", "商品", "规格", "数量");
//写入标题
writer.writeHeadRow(rowHead);
//定义启始行
int index = 1;
List<List<Object>> rows = new LinkedList<>();
//按照姓名分组数据汇总处理(lambda表达式,不了解可以百度)
Map<String, List<OrderExportVo>> staffNoGroupMaps =
orderExportVos.stream().collect(Collectors.groupingBy(OrderExportVo::getDriverUser, Collectors.toList()));
for (Map.Entry<String, List<OrderExportVo>> listEntry : staffNoGroupMaps.entrySet()) {
List<OrderExportVo> staffNoList = listEntry.getValue();
//根据数据条数设置合并单元格信息
if (staffNoList.size() == 1) {//一条数据不合并
index = index + staffNoList.size();
} else {
//规则编写
writer.merge(index, index + staffNoList.size() - 1, 0, 0,
null, true); // 标题
index = index + staffNoList.size();
}
//保存数据
staffNoList.forEach(
sList -> {
List<Object> rowA = null;
rowA = CollUtil.newArrayList(
sList.getDriverUser()
, sList.getGoodsName()
, sList.getSpecification()
, sList.getCount()
);
rows.add(rowA);
}
);
}
//导出数据
// 一次性写出内容,使用默认样式,强制输出标题
writer.write(rows, true);
}
//response为HttpServletResponse对象
response.setContentType("application/vnd.ms-excel;charset=utf-8");
//test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码
response.setHeader("Content-Disposition", DateUtils.getDate("yyyyMMddHHmmss") + ".xlsx");
ServletOutputStream out = response.getOutputStream();
writer.flush(out, true);
//此处记得关闭输出Servlet流
IoUtil.close(out);
return null;
}
正文完