java 大数据EXCEL导出

1、需要加载以下三个包

使用XSSFWorkbook 实现大数据导出,将数据分批从数据库取出,比如一次1万条,然后按顺序生成相应的EXCEL文件,再通过压缩处理,将生成的EXCEL文件压缩为ZIP包,下载该包

poi-ooxml-3.17.jar、poi-3.17.jar、hutool-all-4.0jar

在项目的pom.xml的dependencies中加入以下内容:


    org.apache.poi
    poi
    3.17



    org.apache.poi
    poi-ooxml
    3.17


    cn.hutool
    hutool-all
    4.0.9

2、实现生成EXCEL文件类
/**
* 生成EXCEL文件
* @param fileName 文件名称
* @param path 所在服务器路径
* @param headers 标题

* @param list 数据列表
* @throws Exception
*/

public static void createExcel(String fileName,String path,String[] headers,List list) throws Exception{
XSSFWorkbook workbook = new XSSFWorkbook();
        SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(workbook, 100);
        
        Sheet sheet = sxssfWorkbook.createSheet("sheet");
        Row row = sheet.createRow(0);


        for(int i=0;i            row.createCell(i).setCellValue(headers[i]);
        }
        
        int k =1;
        for(Object[] l : list){//行
            row = sheet.createRow(k++);
            
            int c = 0;
        for(Object o:l){//列
        CellUtil.createCell(row, c++, String.valueOf(o));
        }
        }
        FileOutputStream out = new FileOutputStream(path+fileName);
        sxssfWorkbook.write(out);
        out.close();

}

3、生成ZIP包,并将excel文件删除
public static void main(String[] args) throws Exception {
Date d = new Date();
String basePath = "d:/excelzip/";
String path = basePath+UUID.randomUUID().toString()+"/";
File dir = new File(path);
if(!dir.exists()){
dir.mkdir();
}

String fileName = "wb";
//表头
String[] headers = {"ID","NAME","EMAIL","SCORE"};
//数据
for(int i=1;i<4;i++){
List list = new ArrayList();
for(int j=1;j<10000;j++){
Object[] o = {i*10000+j,i+"-A-"+j,"A"+j+"@qq.com",Math.random()};
list.add(o);
}
createExcel(fileName+"_"+i+".xlsx",path,headers,list);
}


ZipUtil.zip(path,basePath+fileName+".zip");
FileUtils.deleteDirectory(dir);

        System.out.println(new Date().getTime()-d.getTime());

}

4、通过浏览器下载
public ModelAndView down(HttpServletRequest request,
HttpServletResponse response) throws IOException {
String fileName = "wb";
OutputStream  out = response.getOutputStream();  
response.reset();// 清空输出流  
        response.setContentType("application/octet-stream;charset=UTF-8");  
        response.setHeader("Content-Disposition", "attachment;filename="  
                +new String(fileName.getBytes("GB2312"), "8859_1")  
                + ".zip");  
        response.addHeader("Pargam", "no-cache");  
        response.addHeader("Cache-Control", "no-cache");  
        
File zip = new File("d:/excelzip/wb.zip");


   FileInputStream inStream = new FileInputStream(zip);          
   byte[] buf = new byte[4096];  
   int readLenght;  
   while((readLenght = inStream.read(buf)) != -1 ){  
       out.write(buf,0,readLenght);  
   }  
   inStream.close();     
   out.close();  
    return null;
}

你可能感兴趣的:(java)