easyExcel通过流的方式直接传给前端

easyExcel通过流的方式直接传给前端

记录easyExcel的一次实战

@Override
public void warehouserExcel(ResultDto resultDto, HttpServletResponse response) {
    //获取模板
    ClassPathResource classPathResource = new ClassPathResource("/excel/template/warehouse.xlsx");

    //输入流
    InputStream inputStream = null;
    //输出流
    ServletOutputStream outputStream = null;
    //处理填充数据
    DrugMasterEntity drugMasterEntity = getDate(resultDto);
    List<DrugDetailEntity> drugDetailEntityList = drugMasterEntity.getDrugDetails();

    ExcelWriter excelWriter = null;
    try {
        //输入流
        inputStream = classPathResource.getInputStream();
        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");

        String fileName = URLEncoder.encode("result", "UTF-8");
        response.setHeader("Content-disposition", "attachment;filename=" + fileName + ".xlsx");
        outputStream = response.getOutputStream();

        excelWriter = EasyExcel.write(outputStream).withTemplate(inputStream).build();
        WriteSheet writeSheet = EasyExcel.writerSheet().build();
        FillConfig fillConfig = FillConfig.builder().forceNewRow(Boolean.TRUE).build();
        excelWriter.fill(drugDetailEntityList, fillConfig, writeSheet);
        excelWriter.fill(drugMasterEntity, writeSheet);

        outputStream.flush();

        excelWriter.finish();
    } catch (IOException e) {
        e.printStackTrace();
        throw new RuntimeException("导出入库单出错!");
    } finally {
        // 千万别忘记finish 会帮忙关闭流
        if (excelWriter != null) {
            excelWriter.finish();
        }
        //关闭流
        if (outputStream != null) {
            try {
                outputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
        if (inputStream != null) {
            try {
                inputStream.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
}

借鉴了这位大佬https://blog.csdn.net/qq_53804496/article/details/126159181

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值