字节流
@PostMapping("/downloadExcel")
public ResponseEntity<byte[]> downloadExcel() throws Exception {
// Excel文件名
String fileName = "StockInfo.xlsx";
// 使用ByteArrayOutputStream作为输出流
ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
ExcelWriter excelWriter = EasyExcel.write(byteArrayOutputStream).build();
WriteSheet writeSheet = EasyExcel.writerSheet("Data Sheet").build();
// 准备要写入的数据
List<List<Object>> data = new ArrayList<>();
data.add(Arrays.asList("1","2","3","4","5","6"));
// 将数据写入Excel
excelWriter.write(data, writeSheet);
// 关闭ExcelWriter
excelWriter.finish();
// 设置HTTP头部信息
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, "UTF-8"));
// 返回ResponseEntity,包含Excel文件内容和头部信息
return ResponseEntity.ok().headers(headers).body(byteArrayOutputStream.toByteArray());
}
文件流
@PostMapping("/downloadExcel")
public ResponseEntity<Resource> downloadExcel() throws Exception {
// Excel文件名
String fileName = "StockInfo.xlsx";
// 创建Excel文件在服务器的临时存储路径
File tempFile = File.createTempFile("StockInfo", ".xlsx");
// 使用FileOutputStream作为输出流
FileOutputStream fileOutputStream = new FileOutputStream(tempFile);
ExcelWriter excelWriter = EasyExcel.write(fileOutputStream).build();
WriteSheet writeSheet = EasyExcel.writerSheet("Data Sheet").build();
// 准备要写入的数据
List<List<Object>> data = new ArrayList<>();
data.add(Arrays.asList("1","2","3","4","5","6"));
// 将数据写入Excel
excelWriter.write(data, writeSheet);
// 关闭ExcelWriter
excelWriter.finish();
// 关闭文件输出流
fileOutputStream.close();
// 设置HTTP头部信息
HttpHeaders headers = new HttpHeaders();
headers.setContentType(MediaType.parseMediaType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"));
headers.setContentDispositionFormData("attachment", URLEncoder.encode(fileName, "UTF-8"));
// 使用FileSystemResource包装文件,以便于在HTTP响应中传输
Resource resource = new FileSystemResource(tempFile);
// 返回ResponseEntity,包含Excel文件内容和头部信息
return ResponseEntity.ok().headers(headers).contentLength(resource.contentLength()).body(resource);