准备
官方网站:https://www.hutool.cn/docs/#/

public static void writeExcel(HttpServletResponse response, ExcelWriter writer, String fileName) { //response为HttpServletResponse对象 response.setContentType("application/vnd.ms-excel;charset=utf-8"); //test.xls是弹出下载对话框的文件名,不能为中文,中文请自行编码 response.setHeader("Content-Disposition", "attachment;filename=" + fileName); ServletOutputStream servletOutputStream = null; try { servletOutputStream = response.getOutputStream(); //Workbook workbook = writer.getWorkbook(); // workbook.write(servletOutputStream); writer.flush(servletOutputStream); servletOutputStream.flush(); } catch (IORuntimeException | IOException e) { e.printStackTrace(); } finally { writer.close(); try { if (servletOutputStream != null) { servletOutputStream.close(); } } catch (IOException e) { e.printStackTrace(); } } }
步骤1

/** * 表头 * * @param writer 导出文件 * @param titleName 表头参数 */ private void header(ExcelWriter writer, List<String> titleName) { int headerCol = -1; for (String typeName : titleName) { ExcelHelper.mergeIfNeed(writer, 0, 0, ++headerCol, headerCol + 2, 20, typeName); writer.writeCellValue(headerCol, 1, "序号"); writer.writeCellValue(++headerCol, 1, "名称"); writer.writeCellValue(++headerCol, 1, "联系人"); } }
步骤2
表格之间计算 row col i 根据自己的需求调整

/** * 导出数据 * * @param writer 文件 * @param mainList 数据 * @param titleName 表头 */ private void body(ExcelWriter writer, List<SourcePatrolMain> mainList, List<String> titleName) { int row = 1; int col = 0; int i = 0; for (String title : titleName) { i++; int nub = 1; //这里筛选数据每个表头数据 for (SourcePatrolMain main : 筛选数据) { col = 3 * i == 3 ? 0 : 3 * (i - 1); row++; writer.writeCellValue(col++, row, nub++); writer.writeCellValue(col++, row, main.getMianName()); writer.writeCellValue(col++, row,main.getManager()+" "+ main.getPhone()); } row = 1; } }
步骤3
/* * titleList 表头 * mainList 导出数据 */ ExcelWriter writer = ExcelUtil.getWriter(); header(writer, titleList); body(writer, mainList, titleList); ExcelHelper.writeExcel(response, writer, "fileName.xls");