poi概述 Apache POI是Apache软件基金会的开放源码函式库,POI提供API给Java程序对Microsoft Office格式档案读和写的功能。
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 IOException */ 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(){ DecimalFormat 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。 数据结果 excel数据 之前处理百万数据的时候,为了方便,直接把数据存入到了内存,可想而知,总是出现oom异常信息,被总监训了一顿,后来找了一些资料,找到了poi组件。 现在好了,使用poi组件,大大提高了性能,也没有出现oom的情况了,总监很满意,客户也很满意,总算给客户一个较好的体验了。 如果你用java实现处理excel数据时,建议你尝试用poi组件试试。 对于excel数据处理,不知道您有没有更好的组件推荐。 由于笔者知识水平有限,文中错漏之处在所难免,如有不足之处,欢迎纠正,感谢。
|