您的位置 首页 java

java将百万级别数据导出到Excel中,用时仅需要98941毫秒

程序员创业记

跟大家分享一款 excel 组件,之所以分享这款,是因为它在处理excel时很方便,我将百万数据导出到excel,耗时仅不用两分钟。

poi 概述

java将百万级别数据导出到Excel中,用时仅需要98941毫秒

poi

ide: Intellij IDEA

类库 需求poi: 3.17

Excel 版本是2007-2010,我们知道,excel一张表最大支持1048576行,16384列。要将百万级别的数据导出到excel,可接近excel单张表的存款大小了。

poi接入到spring boot ,并不复杂,简单两步就可以完成了。

pom 中引入配置,编写个辅助类

1、pom文件

pom配置poi组件

源码如下:

 <!-- excel依赖 -->
<dependency>
 <groupId>org.apache.poi</groupId>
 <artifactId>poi</artifactId>
 <version>3.17</version>
</dependency>
<dependency>
 <groupId>org.apache.poi</groupId>
 <artifactId>poi-ooxml</artifactId>
 <version>3.17</version>
</dependency>
<dependency>
 <groupId>org.apache.poi</groupId>
 <artifactId>poi-ooxml-schemas</artifactId>
 <version>3.17</version>
</dependency>  
 /**
 * POI辅助类
 */public class POIUtil {
 /**
 * 导出到excel
 * @param filePath 文件存储路径
 * @throws IO Exception 
 */ public  static   void  exportExcel(String filePath) throws IOException {
 //1.在内存中创建一个excel文件
 SXSSFWorkbook sxssfWorkbook = new SXSSFWorkbook(100);
 //2.创建 工作簿 
 Sheet sheet = sxssfWorkbook.createSheet("数据");
 for (int i = 0; i < 1000000; i++) {
 Row row = sheet.createRow(i);
 for (int j = 0; j < 11; j++) {
 if(i == 0) {
 //3.创建标题行
 row.createCell(j).setCellValue(" 列" + j);
 } else {
 //4.遍历数据,创建数据行
 if (j == 0) {
 CellUtil.createCell(row, j, String.valueOf(i));
 } else
 CellUtil.createCell(row, j, String.valueOf(getData()));
 }
 }
 }
  FileOutputStream  out = new FileOutputStream(filePath);
 sxssfWorkbook.write(out);
 out.close();
 }

 /**
 * 填充数据
 * @return
 */ public static String getData(){
  Decimal Format df = new DecimalFormat("######0.00");
 double shoot= Math.random();
 return df.format(shoot);
 }  

程序运行入口

 public class Main {
 final static String path = "E:data.xlsx";

 public static void main(String[] args) throws Exception {
 long beginTime = System.currentTimeMillis();
 POIUtil.exportExcel(path);
 long endTime = System.currentTimeMillis();
 System.out.println("耗时:" + (endTime - beginTime));
 }
}  

耗时:98941

一百万条数据,11列,文件大小有30多M。

数据结果

java将百万级别数据导出到Excel中,用时仅需要98941毫秒

excel数据

之前处理百万数据的时候,为了方便,直接把数据存入到了内存,可想而知,总是出现oom异常信息,被总监训了一顿,后来找了一些资料,找到了poi组件。

现在好了,使用poi组件,大大提高了性能,也没有出现oom的情况了,总监很满意,客户也很满意,总算给客户一个较好的体验了。

如果你用java实现处理excel数据时,建议你尝试用poi组件试试。

对于excel数据处理,不知道您有没有更好的组件推荐。

由于笔者知识水平有限,文中错漏之处在所难免,如有不足之处,欢迎纠正,感谢。

文章来源:智云一二三科技

文章标题:java将百万级别数据导出到Excel中,用时仅需要98941毫秒

文章地址:https://www.zhihuclub.com/184529.shtml

关于作者: 智云科技

热门文章

发表回复

您的电子邮箱地址不会被公开。

网站地图