poi导出百万数据到excel解决方案

    /**
     * 百万数据导出excel方法(使用SXSSFWorkbook):
     *       1.减少对象产生,尽量不要单元格样式和字体样式
     *         2.将对象存入磁盘临时文件
     */
    public void export() throws IOException {
        //1.获取数据
        List<Paper> list = 查询的数据;
        //2.创建工作簿,阈值:内存中的对象数量最大数量,超过就会将对象不断的写入磁盘临时文件
        SXSSFWorkbook wb = new SXSSFWorkbook(100); 
        //3.构造sheet
        Sheet sheet = wb.createSheet();
        //4.创建标题
        String [] titles = "论文名称,第一作者姓名".split(",");
        Row row = sheet.createRow(0);
        int titleIndex=0;
        for (String title : titles) {
            Cell cell = row.createCell(titleIndex++);
            cell.setCellValue(title);
        }
        //5.填充数据
        int rowIndex = 1;
        Cell cell=null;
        for (Paper paper : list) {
            row = sheet.createRow(rowIndex++);
            // 论文名称
            cell = row.createCell(0);
            cell.setCellValue(paper.getName());
            // 第一作者姓名
            cell = row.createCell(1);
            cell.setCellValue(paper.getFirstAuthorName());
        }
        //6.完成下载
        ByteArrayOutputStream os = new ByteArrayOutputStream();
        wb.write(os);
        DownloadUtils.download(os,response,"论文信息.xlsx");
    }

 

package com.*;

import org.apache.commons.io.output.ByteArrayOutputStream;

import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

public class DownloadUtils {

    public static void download(ByteArrayOutputStream byteArrayOutputStream, HttpServletResponse response, String fileName) throws IOException {
        response.setContentType("application/octet-stream");
        fileName = response.encodeURL(new String(fileName.getBytes(),"iso8859-1"));//文件名乱码问题解决
        response.addHeader("Content-Disposition","attachment;filename="+ fileName);
        response.setContentLength(byteArrayOutputStream.size());
        response.addHeader("Content-Length", "" + byteArrayOutputStream.size());
        ServletOutputStream outputstream = response.getOutputStream();    //取得输出流
        byteArrayOutputStream.writeTo(outputstream);                    //写到输出流
        byteArrayOutputStream.close();                                    //关闭
        outputstream.flush();                                            //刷数据
    }
}

 

posted @ 2020-12-22 22:43  lost_s  阅读(200)  评论(0编辑  收藏  举报