为了返回文件流给前端下载,需要针对response类进行操作,如:
import javax.servlet.http.HttpServletResponse;
public JsonResult<String> exportExcel(HttpServletResponse response, String fileName, List<T>[] lists, String[] sheetNames, String path) throws Exception {
if (lists.length != sheetNames.length) return JsonResult.fail("数组长度不一致");
response.setContentType("application/vnd.ms-excel");
response.setHeader("Content-Disposition", "attachment; filename=" + ExcelFragment.encodingFilename(fileName));
OutputStream out = response.getOutputStream();
workbook = new HSSFWorkbook();// 产生工作薄对象
// ... (remaining code)
try {
workbook.write(out);
return JsonResult.success(fileName);
} finally {
out.flush();
out.close();
}
}
设置了ContentType和Header。
并对stream流数据进行了write。
导出后,后端生成的文件名变成了:%E4%B8%80%E7%BA%A7%E5%88%86%E8%B4%A7%E5%B7%A6%E4%B8%8A%E6%90%9C%E7%B4%A2%E6%A1%86%E6%95%
乱码了,应该进行设置Content-Disposition头进行URL 解码。
如:
import java.net.URLDecoder;
// ...
public JsonResult<String> exportExcel(HttpServletResponse response, String fileName, List<T>[] lists, String[] sheetNames, String path) throws Exception {
if (lists.length != sheetNames.length) return JsonResult.fail("数组长度不一致");
response.setContentType("application/vnd.ms-excel");
// 解码 URL 编码的文件名
fileName = URLDecoder.decode(fileName, "UTF-8");
response.setHeader("Content-Disposition", "attachment; filename=" + fileName + ".xlsx");
OutputStream out = response.getOutputStream();
workbook = new HSSFWorkbook();// 产生工作薄对象
// ...(其余代码)
try {
workbook.write(out);
return JsonResult.success(fileName);
} finally {
out.flush();
out.close();
}
}
通过使用 URLDecoder.decode(fileName, “UTF-8”),在设置 Content-Disposition 头之前对文件名进行了 URL 解码。这样应该确保文件名以中文字符正确显示。
另付文件名拼接方法:
protected String assemblyFileNameForXlsx(String name) throws UnsupportedEncodingException {
// 获取当前日期和时分秒
LocalDateTime currentDateTime = LocalDateTime.now();
// 格式化日期时间字符串
String formattedDateTime = currentDateTime.format(DateTimeFormatter.ofPattern("yyyyMMdd_HHmmss"));
// 拼接文件名
String fileName = URLEncoder.encode(name + formattedDateTime, "UTF-8") + ".xlsx";
return fileName;
}