java导出excel,返回前端文件流

该博客介绍了如何从数据库中读取数据并将其转换为Excel格式,利用Apache POI库生成Excel工作簿。内容涉及设置导出参数,限制数据量以避免超时,以及将工作簿写入字节数组。然后,通过Servlet将字节数组作为文件流返回到HTTP响应,设置正确的MIME类型和文件名,确保文件下载成功。
摘要由CSDN通过智能技术生成
1,读取数据库,放到Excel中,返回byte数组 

import org.apache.commons.io.output.ByteArrayOutputStream;
import org.apache.dubbo.config.annotation.Reference;
import org.apache.poi.ss.usermodel.Workbook;
import org.jeecgframework.poi.excel.ExcelExportUtil;
import org.jeecgframework.poi.excel.entity.ExportParams;
import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
import org.springframework.stereotype.Component;

   public byte[] export(Log log, String startTime, String endTime) {
        ExportParams exportParams = new ExportParams(null, null, ExcelType.XSSF);
        Workbook workbook = null;
        //最大100条数据,日志太多,导致超时,而且数据没有什么意义,当然要根据需求来,数据量大可以用队列异步导出,在线等就用多线程导出
       List<Log> logList = logService.getPageList(new Page<>(0, 100), log, startTime, endTime).getRecords();
            workbook = ExcelExportUtil.exportBigExcel(exportParams, Log.class, logList);
        try {
            ByteArrayOutputStream out = new ByteArrayOutputStream();
            if (workbook != null) {
                workbook.write(out);
            }
            return out.toByteArray();
        } catch (IOException e) {
            throw new RuntimeException("文件下载失败", e);
        }
    }
2,把读取文件流,放到response中
import org.apache.commons.io.IOUtils;

public void outExcelFile(HttpServletResponse response, String fileName, byte[] data) {
    try {
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setHeader("Content-Disposition",
                "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO-8859-1"));
        ServletOutputStream outputStream = response.getOutputStream();
        IOUtils.write(data, outputStream);
    } catch (Exception e) {
        throw new RuntimeException("下载文件失败");
    }

}
  • 1
    点赞
  • 17
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值