Java导出商品数据到Excel并按分类小计
要将商品数据下载到Excel文档并通过商品分类进行小计,可以使用Java中的Apache POI库。
首先,需要创建一个Excel文档对象并添加一个工作表:
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet('商品数据');
然后,将商品数据从数据库中查询出来,并按照商品分类进行分组:
List<Product> products = productService.getAllProducts();
Map<String, List<Product>> productMap = products.stream()
.collect(Collectors.groupingBy(Product::getCategory));
接下来,遍历商品分类,将每个分类的商品数据写入Excel文档中,并进行小计:
int rowIndex = 0;
for (String category : productMap.keySet()) {
// 写入分类名称
Row categoryRow = sheet.createRow(rowIndex++);
categoryRow.createCell(0).setCellValue(category);
// 写入商品数据
List<Product> categoryProducts = productMap.get(category);
for (Product product : categoryProducts) {
Row productRow = sheet.createRow(rowIndex++);
productRow.createCell(0).setCellValue(product.getName());
productRow.createCell(1).setCellValue(product.getPrice());
productRow.createCell(2).setCellValue(product.getQuantity());
}
// 进行小计
Row totalRow = sheet.createRow(rowIndex++);
totalRow.createCell(0).setCellValue('小计');
totalRow.createCell(1).setCellFormula("SUM(B" + (rowIndex - categoryProducts.size() - 1) + ":B" + (rowIndex - 2) + ")");
totalRow.createCell(2).setCellFormula("SUM(C" + (rowIndex - categoryProducts.size() - 1) + ":C" + (rowIndex - 2) + ")");
}
最后,将Excel文档保存到本地文件中:
FileOutputStream outputStream = new FileOutputStream("商品数据.xlsx");
workbook.write(outputStream);
outputStream.close();
原文地址: https://www.cveoy.top/t/topic/kSKG 著作权归作者所有。请勿转载和采集!