To implement Excel downloading in a web application (e.g., using Spring Boot), you need to configure the HttpServletResponse headers to ensure the browser treats the response as a file download.
Key steps:
- Set the
ContentType to application/vnd.openxmlformats-officedocument.spreadsheetml.sheet. - Set the character encoding to
utf-8. - Set the
Content-disposition header to attachment and encode the filename using URLEncoder to prevent Chinese character corruption. - Use
EasyExcel.write(response.getOutputStream(), YourDataClass.class).sheet("SheetName").doWrite(data) to stream the file directly to the response output stream.
Note: EasyExcel will automatically close the OutputStream when the operation finishes.
Warning: If using Swagger, you may encounter issues with file downloads; it is recommended to test using a direct browser request or Postman.
@GetMapping("download")
public void download(HttpServletResponse response) throws IOException {
response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
response.setCharacterEncoding("utf-8");
// Prevent Chinese character corruption
String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
// Write data directly to the response output stream
EasyExcel.write(response.getOutputStream(), DownloadData.class)
.sheet("模板")
.doWrite(data());
}