Springboot导出excel,返回excel数据流

用于返回excel数据流到客户端,HSSFWorkbook是创建好的excel文件,fileName是返回的文名。

    private void responseExcel(HSSFWorkbook wk, String fileName, HttpServletResponse response) {
        response.reset();
        response.setContentType("Application/vnd.ms-excel;charset=UTF-8");
        ServletOutputStream out = null;

        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        try {
            response.setHeader("Content-Disposition", "attachment;filename=" + URLEncoder.encode(fileName, "utf-8"));
            out = response.getOutputStream();

            wk.write(outputStream);
            byte[] bookByteAry = outputStream.toByteArray();
            InputStream in = new ByteArrayInputStream(bookByteAry);
            
//             读取文件流
            int len = 0;
            byte[] buffer = new byte[1024 * 10];
            while ((len = in.read(buffer)) != -1) {
                out.write(buffer, 0, len);
            }
            out.flush();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

你可能感兴趣的:(Springboot导出excel,返回excel数据流)