post方法下載excel

chenxiangxiang發表於2024-03-19
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;
}

相關文章