excel 输出demo(outputstream 转inputstr)

发布时间 2023-08-16 17:48:16作者: 咔咔皮卡丘
protected void responseExcel(HSSFWorkbook workbook) throws IOException {
    ByteArrayOutputStream os = new ByteArrayOutputStream();
    try {
        workbook.write(os);
    } catch (IOException e) {
        e.printStackTrace();
    }
    byte[] content = os.toByteArray();
    InputStream is = new ByteArrayInputStream(content);

    //文件名
    String fileName = CodecUtil.getCurrTimeAndRandom();
    response.reset();
    response.setContentType("application/vnd.ms-excel;charset=utf-8");
    response.setHeader("Content-Disposition", "attachment;filename="+ new String((fileName + ".xls").getBytes(), "iso-8859-1"));
    ServletOutputStream out = response.getOutputStream();
    BufferedInputStream bis = null;
    BufferedOutputStream bos = null;
    try {
        bis = new BufferedInputStream(is);
        bos = new BufferedOutputStream(out);
        byte[] buff = new byte[2048];
        int bytesRead;
        // Simple read/write loop.
        while (-1 != (bytesRead = bis.read(buff, 0, buff.length))) {
            bos.write(buff, 0, bytesRead);
        }
    } catch (final IOException e) {
        throw e;
    } finally {
        if (bis != null)
            bis.close();
        if (bos != null)
            bos.close();
    }
}