Java POI Excel 表格合并单元格并计算合计行 - 使用 List<AmcOfficeinfosUtil> 数据
要实现这个需求,可以按照以下步骤进行操作:\n\n1. 创建一个新的 Excel 文档对象:\njava\nWorkbook workbook = new XSSFWorkbook();\nSheet sheet = workbook.createSheet("Sheet1");\n\n\n2. 创建标题行并设置单元格格式:\njava\nRow headerRow = sheet.createRow(0);\nCell headerCell1 = headerRow.createCell(0);\nheaderCell1.setCellValue("名称");\nCell headerCell2 = headerRow.createCell(1);\nheaderCell2.setCellValue("规格");\nCell headerCell3 = headerRow.createCell(2);\nheaderCell3.setCellValue("部门");\nCell headerCell4 = headerRow.createCell(3);\nheaderCell4.setCellValue("申请人");\n\nCellStyle headerCellStyle = workbook.createCellStyle();\nheaderCellStyle.setAlignment(HorizontalAlignment.CENTER);\nheaderCell1.setCellStyle(headerCellStyle);\nheaderCell2.setCellStyle(headerCellStyle);\nheaderCell3.setCellStyle(headerCellStyle);\nheaderCell4.setCellStyle(headerCellStyle);\n\n\n3. 遍历数据集合,依次将数据写入 Excel 表格中的单元格:\njava\nList<AmcOfficeinfosUtil> dataList = ...; // 数据集合\nint rowIndex = 1; // 数据行索引,从第二行开始\n\nfor (AmcOfficeinfosUtil data : dataList) {\n Row row = sheet.createRow(rowIndex);\n Cell cell1 = row.createCell(0);\n cell1.setCellValue(data.getName());\n Cell cell2 = row.createCell(1);\n cell2.setCellValue(data.getSpecification());\n Cell cell3 = row.createCell(2);\n cell3.setCellValue(data.getDepartment());\n Cell cell4 = row.createCell(3);\n cell4.setCellValue(data.getApplicant());\n\n rowIndex++;\n}\n\n\n4. 合并相同数据的单元格:\njava\nint rowCount = sheet.getLastRowNum() + 1;\n\nfor (int i = 1; i < rowCount; i++) {\n Cell currentCell = sheet.getRow(i).getCell(0);\n Cell previousCell = sheet.getRow(i - 1).getCell(0);\n\n if (currentCell.getStringCellValue().equals(previousCell.getStringCellValue())) {\n sheet.addMergedRegion(new CellRangeAddress(i - 1, i, 0, 0));\n }\n}\n\n\n5. 添加合计行计算相同名称的数量:\njava\nMap<String, Integer> countMap = new HashMap<>();\n\nfor (int i = 1; i < rowCount; i++) {\n Cell cell = sheet.getRow(i).getCell(0);\n String name = cell.getStringCellValue();\n\n if (countMap.containsKey(name)) {\n countMap.put(name, countMap.get(name) + 1);\n } else {\n countMap.put(name, 1);\n }\n}\n\nRow totalRow = sheet.createRow(rowCount);\nCell totalCell1 = totalRow.createCell(0);\ntotalCell1.setCellValue("合计");\n\nint columnIndex = 1;\nfor (String name : countMap.keySet()) {\n Cell totalCell = totalRow.createCell(columnIndex);\n totalCell.setCellValue(countMap.get(name));\n columnIndex++;\n}\n\n\n6. 将 Excel 文档写入文件或输出流:\njava\nFileOutputStream outputStream = new FileOutputStream("output.xlsx");\nworkbook.write(outputStream);\nworkbook.close();\noutputStream.close();\n\n\n以上是一个简单的实现示例,你可以根据实际需求进行适当的修改和调整。
原文地址: http://www.cveoy.top/t/topic/puyZ 著作权归作者所有。请勿转载和采集!