java poi execl表格根据数据集合listAmcOfficeinfosUtil数量名称、规格、部门、申请人数据相同的单元格分别进行合并 并且在最后有合计行计算名称相同的数量相加
要实现这个需求,可以按照以下步骤进行操作:
- 创建一个新的Excel文档对象:
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet("Sheet1");
- 创建标题行并设置单元格格式:
Row headerRow = sheet.createRow(0);
Cell headerCell1 = headerRow.createCell(0);
headerCell1.setCellValue("名称");
Cell headerCell2 = headerRow.createCell(1);
headerCell2.setCellValue("规格");
Cell headerCell3 = headerRow.createCell(2);
headerCell3.setCellValue("部门");
Cell headerCell4 = headerRow.createCell(3);
headerCell4.setCellValue("申请人");
CellStyle headerCellStyle = workbook.createCellStyle();
headerCellStyle.setAlignment(HorizontalAlignment.CENTER);
headerCell1.setCellStyle(headerCellStyle);
headerCell2.setCellStyle(headerCellStyle);
headerCell3.setCellStyle(headerCellStyle);
headerCell4.setCellStyle(headerCellStyle);
- 遍历数据集合,依次将数据写入Excel表格中的单元格:
List<AmcOfficeinfosUtil> dataList = ...; // 数据集合
int rowIndex = 1; // 数据行索引,从第二行开始
for (AmcOfficeinfosUtil data : dataList) {
Row row = sheet.createRow(rowIndex);
Cell cell1 = row.createCell(0);
cell1.setCellValue(data.getName());
Cell cell2 = row.createCell(1);
cell2.setCellValue(data.getSpecification());
Cell cell3 = row.createCell(2);
cell3.setCellValue(data.getDepartment());
Cell cell4 = row.createCell(3);
cell4.setCellValue(data.getApplicant());
rowIndex++;
}
- 合并相同数据的单元格:
int rowCount = sheet.getLastRowNum() + 1;
for (int i = 1; i < rowCount; i++) {
Cell currentCell = sheet.getRow(i).getCell(0);
Cell previousCell = sheet.getRow(i - 1).getCell(0);
if (currentCell.getStringCellValue().equals(previousCell.getStringCellValue())) {
sheet.addMergedRegion(new CellRangeAddress(i - 1, i, 0, 0));
}
}
- 添加合计行计算相同名称的数量:
Map<String, Integer> countMap = new HashMap<>();
for (int i = 1; i < rowCount; i++) {
Cell cell = sheet.getRow(i).getCell(0);
String name = cell.getStringCellValue();
if (countMap.containsKey(name)) {
countMap.put(name, countMap.get(name) + 1);
} else {
countMap.put(name, 1);
}
}
Row totalRow = sheet.createRow(rowCount);
Cell totalCell1 = totalRow.createCell(0);
totalCell1.setCellValue("合计");
int columnIndex = 1;
for (String name : countMap.keySet()) {
Cell totalCell = totalRow.createCell(columnIndex);
totalCell.setCellValue(countMap.get(name));
columnIndex++;
}
- 将Excel文档写入文件或输出流:
FileOutputStream outputStream = new FileOutputStream("output.xlsx");
workbook.write(outputStream);
workbook.close();
outputStream.close();
以上是一个简单的实现示例,你可以根据实际需求进行适当的修改和调整
原文地址: https://www.cveoy.top/t/topic/hLr8 著作权归作者所有。请勿转载和采集!