您可以使用 Apache POI 库来实现这个功能。下面是一个示例代码,展示了如何根据数据集合合并单元格并计算合计行。\n\njava\nimport org.apache.poi.ss.usermodel.*;\nimport org.apache.poi.xssf.usermodel.XSSFWorkbook;\nimport org.apache.poi.ss.util.CellRangeAddress;\n\nimport java.io.FileOutputStream;\nimport java.io.IOException;\nimport java.util.List;\n\npublic class ExcelMergeCells {\n public static void main(String[] args) throws IOException {\n List<AmcOfficeinfosUtil> data = // 获取数据集合\n\n Workbook workbook = new XSSFWorkbook();\n Sheet sheet = workbook.createSheet("Sheet1");\n\n // 创建样式\n CellStyle style = workbook.createCellStyle();\n style.setAlignment(HorizontalAlignment.CENTER);\n\n // 添加数据\n int rowIndex = 0;\n for (AmcOfficeinfosUtil item : data) {\n Row row = sheet.createRow(rowIndex++);\n createCell(row, 0, item.get数量(), style); // 数量\n createCell(row, 1, item.get名称(), style); // 名称\n createCell(row, 2, item.get规格(), style); // 规格\n createCell(row, 3, item.get部门(), style); // 部门\n createCell(row, 4, item.get申请人(), style); // 申请人\n }\n\n // 合并单元格\n mergeCells(sheet, 1, rowIndex); // 合并名称列\n mergeCells(sheet, 2, rowIndex); // 合并规格列\n mergeCells(sheet, 3, rowIndex); // 合并部门列\n mergeCells(sheet, 4, rowIndex); // 合并申请人列\n\n // 添加合计行\n Row totalRow = sheet.createRow(rowIndex++);\n createCell(totalRow, 0, "合计", style);\n createFormulaCell(totalRow, 1, "SUM(B1:B" + (rowIndex - 1) + ")", style); // 计算名称相同数据合并后的数量\n\n // 保存文件\n FileOutputStream fileOut = new FileOutputStream("output.xlsx");\n workbook.write(fileOut);\n fileOut.close();\n\n // 关闭工作簿\n workbook.close();\n }\n\n private static void createCell(Row row, int columnIndex, Object value, CellStyle style) {\n Cell cell = row.createCell(columnIndex);\n if (value instanceof String) {\n cell.setCellValue((String) value);\n } else if (value instanceof Integer) {\n cell.setCellValue((Integer) value);\n }\n cell.setCellStyle(style);\n }\n\n private static void createFormulaCell(Row row, int columnIndex, String formula, CellStyle style) {\n Cell cell = row.createCell(columnIndex);\n cell.setCellFormula(formula);\n cell.setCellStyle(style);\n }\n\n private static void mergeCells(Sheet sheet, int columnIndex, int rowCount) {\n for (int i = 0; i < rowCount; i++) {\n CellRangeAddress range = new CellRangeAddress(i, rowCount - 1, columnIndex, columnIndex);\n sheet.addMergedRegion(range);\n }\n }\n}\n\n\n请注意,这只是一个示例代码,您需要根据实际情况进行修改和调整。


原文地址: https://www.cveoy.top/t/topic/puoG 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录