【实战】excel分页写入导出大文件

java 复制代码
 @RequestMapping("export")
    @ResponseBody
    public void export(HttpServletResponse response) {
        long start = System.currentTimeMillis();
        QueryVo query = new QueryVo();

        // response响应头
        setResponseHeader(response, "excel");
        ExcelWriter writer = ExcelUtil.genExcelWriter(response);
        // 表格
        WriteTable table = new WriteTable();
        WriteSheet sheet = new WriteSheet();
        sheet.setSheetNo(1);
        sheet.setSheetName("excel");
        writer.write(Lists.newArrayList(),sheet,table);

        int pageNo=1;
        query.setPageSize(exportPageSize);
        int index = 0;

        while (true) {
            // 构造分页信息
            int offset = exportPageSize * (pageNo++ - 1);
            query.setOffset(offset);
            // 查询一页数据
            List<Pharmacist> list = mybatisDao.getList(query);
            if (CollectionUtils.isEmpty(list)) {
                break;
            }
            // 分批写入
            writer.write(list,sheet);
        }
        long end = System.currentTimeMillis();
        log.info("导出excel耗时:{}", end - start);
        writer.finish();

    }

工具类

java 复制代码
import com.alibaba.excel.EasyExcel;
import com.alibaba.excel.ExcelWriter;
import com.alibaba.excel.write.metadata.style.WriteCellStyle;
import com.alibaba.excel.write.metadata.style.WriteFont;
import com.alibaba.excel.write.style.HorizontalCellStyleStrategy;
import com.example.demo.utils.BizException;
import com.example.demo.utils.JsonUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.poi.ss.usermodel.HorizontalAlignment;
import org.apache.poi.ss.usermodel.VerticalAlignment;

import javax.servlet.http.HttpServletResponse;
import java.io.InputStream;

/**
 * @Description: excel工具
 */
@Slf4j
public class ExcelUtil {

    /**
     * 读取excel并处理数据
     * @param inputStream
     * @param dataInfo  function中处理的数据文件格式为 List<List<String>>
     */
    public static void readExcel(InputStream inputStream,ExcelDataInfo dataInfo){
        log.info("------读取excel文件开始-------");
        ExcelDataListener headerListener = new ExcelDataListener(dataInfo);
        EasyExcel.read(inputStream, null,headerListener).sheet().headRowNumber(1).doRead();
        log.info("------读取excel文件结束-----\n------表头------\n" + JsonUtil.toJson(headerListener.getHeader()));

    }

    /**
     * 读取excel并处理数据
     * @param inputStream
     * @param dataInfo  function中处理的数据文件格式为 List<List<String>>
     */
    public static void readExcel(InputStream inputStream,ExcelDataInfo dataInfo, int headerRow){
        log.info("------读取excel文件开始-------");
        ExcelDataListener headerListener = new ExcelDataListener(dataInfo);
        EasyExcel.read(inputStream, null,headerListener).sheet().headRowNumber(headerRow).doRead();
        log.info("------读取excel文件结束-----\n------表头------\n" + JsonUtil.toJson(headerListener.getHeader()));
    }

    /**
     * 生成writer
     * @param response
     * @return
     */
    public static ExcelWriter genExcelWriter(HttpServletResponse response){
        WriteCellStyle wcs = new WriteCellStyle();
        // 垂直居中、 左对齐
        wcs.setVerticalAlignment(VerticalAlignment.CENTER);
        wcs.setHorizontalAlignment(HorizontalAlignment.LEFT);
        WriteFont wf = new WriteFont();
        wf.setFontHeightInPoints((short)12);
        wcs.setWriteFont(wf);
        // 表头
        WriteCellStyle hwcs = new WriteCellStyle();
        hwcs.setVerticalAlignment(VerticalAlignment.CENTER);
        hwcs.setHorizontalAlignment(HorizontalAlignment.CENTER);
        WriteFont hwf = new WriteFont();
        hwf.setFontHeightInPoints((short)12);
        hwf.setBold(Boolean.TRUE);
        hwcs.setWriteFont(hwf);

        try {
            ExcelWriter writer = EasyExcel.write(response.getOutputStream()).registerWriteHandler(new HorizontalCellStyleStrategy(hwcs,wcs)).build();
            return writer;
        } catch (Exception e) {
            log.error("导出excel失败",e);
            throw new BizException("导出excel失败", e);
        }
    }

    /**
     * 设置导出response响应头
     * @param response
     * @param fileName
     */
    public static void setResponseHeader(HttpServletResponse response,String fileName){

        response.setContentType("application/vnd.ms-excel");
        response.setCharacterEncoding("utf-8");
        response.setHeader("Content-Disposition","attachment;filename="+fileName);
        response.setHeader("Param","no-cache");
        response.setHeader("Cache-Control","no-cache");
    }
}
相关推荐
老白干21 小时前
jjwt 0.9.1 在 JDK 11+ 上的两个“坑”与完整解决方案
java·python·log4j
圆山猫1 天前
[Virtualization](四):Linux KVM/RISC-V 的 vCPU 运行路径
java·linux·risc-v
城管不管1 天前
ReAct、Plan-and-Execute、Reflection 三大智能 Agent 范式核心区别
java·人工智能·算法·spring·ai·动态规划
IT小白杨1 天前
从环境制备到自动化工作流:多账号运营的工程化架构拆解
java·经验分享·自动化·安全架构·指纹浏览器
豆瓣鸡1 天前
算法日记 - Day3
java·开发语言·算法
hPw0eKIqD1 天前
使用二次封装的Excel COM 组件操作Excel\WPS ET中的区域、行和列
excel·wps
萧瑟余晖1 天前
Java深入解析篇九之NIO详解
java·网络·nio
The Chosen One9851 天前
高进度算法模板速记(待完善)
java·前端·算法
极光代码工作室1 天前
基于SpringBoot的课程预约系统
java·springboot·web开发·后端开发
Leighteen1 天前
`try-finally` 里的 `return`:为什么 `finally` 会悄悄改掉返回值、吞掉异常
java·开发语言