@zecaishao/kunchi-table
v0.3.114
Published
kunchi-table
Downloads
19
Readme
以下是一份示范代码,基于 Spring Boot,完成了 Excel 文件上传、解析、查询、排序、导出功能。
@RestController
@RequestMapping(\"/orders\")
public class OrderController {
@Autowired
private ProductService productService;
@PostMapping(\"/upload\")
public ResponseEntity uploadFile(@RequestParam(\"file\") MultipartFile file) throws IOException {
// 读取上传的 Excel 文件
InputStream inputStream = file.getInputStream();
Workbook workbook = WorkbookFactory.create(inputStream);
// 解析文件中的订单号
Set orderIds = new HashSet<>();
Sheet sheet = workbook.getSheetAt(0);
for (Row row : sheet) {
Cell orderIdCell = row.getCell(0);
if (orderIdCell != null && orderIdCell.getCellType() == CellType.STRING) {
orderIds.add(orderIdCell.getStringCellValue());
}
}
// 根据订单号查询商品信息,并按库存数量降序排列
List products = productService.findByOrderIds(orderIds);
Collections.sort(products, Comparator.comparing(Product::getStock).reversed());
// 导出查询结果到 Excel 文件中
Workbook resultWorkbook = new XSSFWorkbook();
Sheet resultSheet = resultWorkbook.createSheet(\"Products\");
int rowIndex = 0;
for (Product product : products) {
Row row = resultSheet.createRow(rowIndex++);
row.createCell(0).setCellValue(product.getName());
row.createCell(1).setCellValue(product.getStock());
}
// 将导出结果保存至文件中
ByteArrayOutputStream outputStream = new ByteArrayOutputStream();
resultWorkbook.write(outputStream);
LocalDate date = LocalDate.now();
String filename = String.format(\"ProductStock-%s.xlsx\", date.toString());
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.APPLICATION_OCTET_STREAM);
headers.setContentDispositionFormData(\"attachment\", filename);
return new ResponseEntity<> (outputStream.toString(), headers, HttpStatus.OK);
}
}
这段代码实现了在 /orders/upload
路径下接收一个名为 file
的文件,并完成对这个文件的解析、查询、排序、导出操作。最终导出的 Excel 文件以附件形式发送给管理员。
开发者需要根据具体业务需求,对代码中的 ProductService 做相应的调整,以保证获取商品信息的正确性。