/** * * @param response HttpServletResponse对象 * @param excelData 数据 * @param headers 表头 * @param sheetName sheet名 * @param fileName 文件名 * @param columnWidth 宽度 * @param rowColumns 指定合并单元格行列 * @throws IOException */ public static void exportExcelForJobLevelSituation(HttpServletResponse response, List<List<String>> excelData, List<String> headers, String sheetName, String fileName, int columnWidth, List<List<Integer>> rowColumns) throws IOException { HSSFWorkbook workbook = new HSSFWorkbook(); HSSFCellStyle style = workbook.createCellStyle(); style.setAlignment(HorizontalAlignment.CENTER); style.setVerticalAlignment(VerticalAlignment.CENTER); //生成一个表格,设置表格名称 HSSFSheet sheet = workbook.createSheet(sheetName); //设置表格列宽度 sheet.setDefaultColumnWidth(columnWidth); //表头 int rowIndex = 0; for(String header : headers){ //创建一个row行 HSSFRow row = sheet.createRow(0); //遍历添加本行数据 for (int i = 0; i < headers.size(); i++) { //创建一个单元格 HSSFCell cell = row.createCell(i); //创建一个内容对象 HSSFRichTextString text = new HSSFRichTextString(header); //将内容对象的文字内容写入到单元格中 cell.setCellValue(text); cell.setCellStyle(style); } } //写入List<List<String>>中的数据 for(List<String> data : excelData){ //创建一个row行,然后自增1 HSSFRow row = sheet.createRow(rowIndex++); //遍历添加本行数据 for (int i = 0; i < data.size(); i++) { //创建一个单元格 HSSFCell cell = row.createCell(i); //创建一个内容对象 HSSFRichTextString text = new HSSFRichTextString(data.get(i)); //将内容对象的文字内容写入到单元格中 cell.setCellValue(text); cell.setCellStyle(style); } } //合并单元格操作 int[] rowOrColum = new int[4]; int index = 0; for (List<Integer> rowColumn : rowColumns) { for (int i = 0; i < rowColumn.size(); i++) { rowOrColum[index] = rowColumn.get(i); index++; } index = 0; sheet.addMergedRegion(new CellRangeAddress(rowOrColum[0],rowOrColum[1],rowOrColum[2],rowOrColum[3])); } //准备将Excel的输出流通过response输出到页面下载 //八进制输出流 response.setContentType("application/octet-stream"); response.setCharacterEncoding("UTF-8"); //设置导出Excel的名称 response.setHeader("Content-disposition", "attachment;filename=" + new String(fileName.getBytes("UTF-8"),"iso8859-1")); //刷新缓冲 response.flushBuffer(); //workbook将Excel写入到response的输出流中,供页面下载该Excel文件 workbook.write(response.getOutputStream()); //关闭workbook workbook.close(); }
调用:
List<List<String>> excelData = statisticalReportService.exportJobLevelSituation(); String sheetName = "*****表"; String fileName = "Excel.xls"; //将所有合并的单元格坐标存入list List<List<Integer>> rowColumns = new ArrayList<>(); List<Integer> rowColumn = new ArrayList<>(); rowColumn.add(13); rowColumn.add(14); rowColumn.add(2); rowColumn.add(2); rowColumns.add(rowColumn); ExcelUtil.exportExcelForMergeCell(response,excelData,StatisticalReportService.headList,sheetName,fileName,25,rowColumns); }