当前位置:   article > 正文

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

java返回excel文件流
  1. 1,读取数据库,放到Excel中,返回byte数组
  1. import org.apache.commons.io.output.ByteArrayOutputStream;
  2. import org.apache.dubbo.config.annotation.Reference;
  3. import org.apache.poi.ss.usermodel.Workbook;
  4. import org.jeecgframework.poi.excel.ExcelExportUtil;
  5. import org.jeecgframework.poi.excel.entity.ExportParams;
  6. import org.jeecgframework.poi.excel.entity.enmus.ExcelType;
  7. import org.springframework.stereotype.Component;
  8. public byte[] export(Log log, String startTime, String endTime) {
  9. ExportParams exportParams = new ExportParams(null, null, ExcelType.XSSF);
  10. Workbook workbook = null;
  11. //最大100条数据,日志太多,导致超时,而且数据没有什么意义,当然要根据需求来,数据量大可以用队列异步导出,在线等就用多线程导出
  12. List<Log> logList = logService.getPageList(new Page<>(0, 100), log, startTime, endTime).getRecords();
  13. workbook = ExcelExportUtil.exportBigExcel(exportParams, Log.class, logList);
  14. try {
  15. ByteArrayOutputStream out = new ByteArrayOutputStream();
  16. if (workbook != null) {
  17. workbook.write(out);
  18. }
  19. return out.toByteArray();
  20. } catch (IOException e) {
  21. throw new RuntimeException("文件下载失败", e);
  22. }
  23. }
2,把读取文件流,放到response中
  1. import org.apache.commons.io.IOUtils;
  2. public void outExcelFile(HttpServletResponse response, String fileName, byte[] data) {
  3. try {
  4. response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
  5. response.setHeader("Content-Disposition",
  6. "attachment;filename=" + new String(fileName.getBytes("gb2312"), "ISO-8859-1"));
  7. ServletOutputStream outputStream = response.getOutputStream();
  8. IOUtils.write(data, outputStream);
  9. } catch (Exception e) {
  10. throw new RuntimeException("下载文件失败");
  11. }
  12. }
声明:本文内容由网友自发贡献,不代表【wpsshop博客】立场,版权归原作者所有,本站不承担相应法律责任。如您发现有侵权的内容,请联系我们。转载请注明出处:https://www.wpsshop.cn/w/知新_RL/article/detail/842566
推荐阅读
相关标签
  

闽ICP备14008679号