post方法下载excel

main{
  
ByteArrayOutputStream outputStream = excelUtil.exportExcel(header, data);
// 返回文件流给前端
String fileName = "fixedSavingExport" + CommUtil.getComputerDate() + ".csv";

return ResponseEntity.ok()
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename="+fileName+"")
.contentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"))
.body(new ByteArrayResource(outputStream.toByteArray()));

}


public ByteArrayOutputStream exportExcel(List<String> header, List<List<String>> data) {
try (Workbook workbook = new XSSFWorkbook();
ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
Sheet sheet = workbook.createSheet("Sheet1");

// 创建表头
Row headerRow = sheet.createRow(0);
for (int i = 0; i < header.size(); i++) {
headerRow.createCell(i).setCellValue(header.get(i));
}

// 填充数据
for (int i = 0; i < data.size(); i++) {
Row dataRow = sheet.createRow(i + 1);
List<String> rowData = data.get(i);
for (int j = 0; j < rowData.size(); j++) {
dataRow.createCell(j).setCellValue(rowData.get(j));
}
}

try {
workbook.write(outputStream);
} catch (IOException e) {
e.printStackTrace();
}

return outputStream;
} catch (IOException e) {
e.printStackTrace();
}

return null;
}
posted @ 2024-03-19 15:25  chenxiangxiang  阅读(58)  评论(0编辑  收藏  举报