@Controller //不能是RestController
@RequestMapping("/excel")
public class ExcelController {
@GetMapping(value = "/export")
public ResponseEntity<StreamingResponseBody> resultExport() throws Exception { //需要加上返回的泛型StreamingResponseBody
List data = new ArrayList();
String[] header = {"一", "二", "三", "四", "五"};
Workbook wb = new XSSFWorkbook();
Sheet sheet = wb.createSheet();
Row row = sheet.createRow(0);
for (int i = 0; i < header.length; i++) {
row.createCell(i).setCellValue(header[i]);
}
for (int x = 0; x < data.size(); x++) {
Row rowNew = sheet.createRow(x + 1);
//data.get(x);
rowNew.createCell(0).setCellValue("");
rowNew.createCell(1).setCellValue("");
rowNew.createCell(2).setCellValue("");
rowNew.createCell(3).setCellValue("");
rowNew.createCell(4).setCellValue("");
}
return ResponseEntity.ok()
.header("Access-Control-Expose-Headers","Content-Disposition") //不加这一行在跨域情况下前端可能会取不到请求头里的Content-Disposition
.header(HttpHeaders.CONTENT_DISPOSITION, "attachment; filename=" + URLEncoder.encode(excelName, "UTF-8")) //文件名
.body(wb::write);
/* 上面一行是这一块儿的lambda抽取
.body(new StreamingResponseBody() {
@Override
public void writeTo(OutputStream outputStream) throws IOException {
wb.write(outputStream);
}
});*/
}
}