该代码是一个用于在 HttpServletResponse 中写入 Excel 文件的方法。

首先,设置响应的 Content-Type 为 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet',表示要写入的是 Excel 文件。

然后,设置响应的字符编码为 'utf-8'。

接下来,对文件名进行 URL 编码,并将空格替换为 '%20'。

最后,设置响应头的 Content-disposition 属性,指定要下载的文件名,并设置编码为 'utf-8'。

最后一行代码使用 EasyExcel 库将数据写入到响应的输出流中,通过 sheet 方法指定工作表的名称为 'sheel1',并调用 doWrite 方法写入数据。

public static <T> void write(HttpServletResponse response, String filename,
                                 Class<T> head, List<T> data) throws IOException {
    response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
    response.setCharacterEncoding("utf-8");
    String fileName = URLEncoder.encode(filename, "UTF-8").replaceAll("\\+", "%20");
    response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
    EasyExcel.write(response.getOutputStream(), head).sheet("sheel1").doWrite(data);
}

原文地址: https://www.cveoy.top/t/topic/piBw 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录