【实战】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");
    }
}
相关推荐
勤奋的知更鸟7 分钟前
Java 编程之策略模式详解
java·设计模式·策略模式
qq_4924484469 分钟前
Java 访问HTTP,信任所有证书,解决SSL报错问题
java·http·ssl
爱上语文12 分钟前
Redis基础(4):Set类型和SortedSet类型
java·数据库·redis·后端
lifallen26 分钟前
Paimon vs. HBase:全链路开销对比
java·大数据·数据结构·数据库·算法·flink·hbase
深栈解码1 小时前
JMM深度解析(三) volatile实现机制详解
java·后端
liujing102329291 小时前
Day04_刷题niuke20250703
java·开发语言·算法
Brookty1 小时前
【MySQL】JDBC编程
java·数据库·后端·学习·mysql·jdbc
能工智人小辰2 小时前
二刷 苍穹外卖day10(含bug修改)
java·开发语言
DKPT2 小时前
Java设计模式之结构型模式(外观模式)介绍与说明
java·开发语言·笔记·学习·设计模式
缘来是庄2 小时前
设计模式之外观模式
java·设计模式·外观模式