准備
官方網站: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");