POI讀寫大數據量excel,解決超過幾萬行而致使內存溢出的問題

1. Excel2003與Excel2007

兩個版本的最大行數和列數不一樣,2003版最大行數是65536行,最大列數是256列,2007版及之後的版本最大行數是1048576行,最大列數是16384列。html

excel2003是以二進制的方式存儲,這種格式不易被其餘軟件讀取使用;而excel2007採用了基於XML的ooxml開放文檔標準,ooxml使用XML和ZIP技術結合進行文件存儲,XML是一個基於文本的格式,並且ZIP容器支持內容的壓縮,因此其一大優點是能夠大大減少文件的尺寸。java

2. 大批量數據讀寫

2.1 大批量數據寫入

對於大數據的Xlsx文件的寫入,POI3.8提供了SXSSFSXSSFWorkbook類,採用緩存方式進行大批量寫文件。git

詳情能夠查看poi官網示例:http://poi.apache.org/spreadsheet/how-to.html#sxssf 或 http://blog.csdn.net/daiyutage/article/details/53010491github

2.2 大批量數據讀取

POI讀取Excel有兩種模式,一種是用戶模式,一種是SAX事件驅動模式,將xlsx格式的文檔轉換成CSV格式後進行讀取。用戶模式API接口豐富,使用POI的API能夠很容易讀取Excel,但用戶模式消耗的內存很大,當遇到很大sheet、大數據網格,假空行、公式等問題時,很容易致使內存溢出。POI官方推薦解決內存溢出的方式使用CVS格式解析,即SAX事件驅動模式。下面主要是講解如何讀取大批量數據:apache

2.2.1 pom.xml所需jar包

複製代碼
 1 <project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
 2   xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/maven-v4_0_0.xsd">
 3   <modelVersion>4.0.0</modelVersion>
 4   <groupId>POIExcel</groupId>
 5   <artifactId>POIExcel</artifactId>
 6   <packaging>war</packaging>
 7   <version>1.0-SNAPSHOT</version>
 8   <name>POIExcel Maven Webapp</name>
 9   <url>http://maven.apache.org</url>
10   <dependencies>
11     <dependency>
12       <groupId>junit</groupId>
13       <artifactId>junit</artifactId>
14       <version>3.8.1</version>
15       <scope>test</scope>
16     </dependency>
17 
18     <dependency>
19       <groupId>org.apache.poi</groupId>
20       <artifactId>poi</artifactId>
21       <version>3.17</version>
22     </dependency>
23 
24     <dependency>
25       <groupId>org.apache.poi</groupId>
26       <artifactId>poi-ooxml</artifactId>
27       <version>3.17</version>
28     </dependency>
29 
30     <dependency>
31       <groupId>org.apache.poi</groupId>
32       <artifactId>poi-ooxml-schemas</artifactId>
33       <version>3.17</version>
34     </dependency>
35 
36     <dependency>
37       <groupId>com.syncthemall</groupId>
38       <artifactId>boilerpipe</artifactId>
39       <version>1.2.1</version>
40     </dependency>
41 
42     <dependency>
43       <groupId>xerces</groupId>
44       <artifactId>xercesImpl</artifactId>
45       <version>2.11.0</version>
46     </dependency>
47 
48     <dependency>
49       <groupId>xml-apis</groupId>
50       <artifactId>xml-apis</artifactId>
51       <version>1.4.01</version>
52     </dependency>
53 
54     <dependency>
55       <groupId>org.apache.xmlbeans</groupId>
56       <artifactId>xmlbeans</artifactId>
57       <version>2.6.0</version>
58     </dependency>
59 
60     <dependency>
61       <groupId>sax</groupId>
62       <artifactId>sax</artifactId>
63       <version>2.0.1</version>
64     </dependency>
65 
66     <dependency>
67       <groupId>org.apache.commons</groupId>
68       <artifactId>commons-lang3</artifactId>
69       <version>3.7</version>
70     </dependency>
71 
72   </dependencies>
73   <build>
74     <finalName>POIExcel</finalName>
75   </build>
76 </project>
複製代碼

2.2.2 POI以SAX解析excel2007文件

解決思路:經過繼承DefaultHandler類,重寫process(),startElement(),characters(),endElement()這四個方法。process()方式主要是遍歷全部的sheet,並依次調用startElement()、characters()方法、endElement()這三個方法。startElement()用於設定單元格的數字類型(如日期、數字、字符串等等)。characters()用於獲取該單元格對應的索引值或是內容值(若是單元格類型是字符串、INLINESTR、數字、日期則獲取的是索引值;其餘如布爾值、錯誤、公式則獲取的是內容值)。endElement()根據startElement()的單元格數字類型和characters()的索引值或內容值,最終得出單元格的內容值,並打印出來。api

複製代碼
  1 package org.poi;
  2 
  3 import org.apache.poi.openxml4j.opc.OPCPackage;
  4 import org.apache.poi.ss.usermodel.BuiltinFormats;
  5 import org.apache.poi.ss.usermodel.DataFormatter;
  6 import org.apache.poi.xssf.eventusermodel.XSSFReader;
  7 import org.apache.poi.xssf.model.SharedStringsTable;
  8 import org.apache.poi.xssf.model.StylesTable;
  9 import org.apache.poi.xssf.usermodel.XSSFCellStyle;
 10 import org.apache.poi.xssf.usermodel.XSSFRichTextString;
 11 import org.xml.sax.Attributes;
 12 import org.xml.sax.InputSource;
 13 import org.xml.sax.SAXException;
 14 import org.xml.sax.XMLReader;
 15 import org.xml.sax.helpers.DefaultHandler;
 16 import org.xml.sax.helpers.XMLReaderFactory;
 17 
 18 import java.io.InputStream;
 19 import java.util.ArrayList;
 20 import java.util.List;
 21 
 22 /**
 23  * @author y
 24  * @create 2018-01-18 14:28
 25  * @desc POI讀取excel有兩種模式,一種是用戶模式,一種是事件驅動模式
 26  * 採用SAX事件驅動模式解決XLSX文件,能夠有效解決用戶模式內存溢出的問題,
 27  * 該模式是POI官方推薦的讀取大數據的模式,
 28  * 在用戶模式下,數據量較大,Sheet較多,或者是有不少無用的空行的狀況下,容易出現內存溢出
 29  * <p>
 30  * 用於解決.xlsx2007版本大數據量問題
 31  **/
 32 public class ExcelXlsxReader extends DefaultHandler {
 33 
 34     /**
 35      * 單元格中的數據可能的數據類型
 36      */
 37     enum CellDataType {
 38         BOOL, ERROR, FORMULA, INLINESTR, SSTINDEX, NUMBER, DATE, NULL
 39     }
 40 
 41     /**
 42      * 共享字符串表
 43      */
 44     private SharedStringsTable sst;
 45 
 46     /**
 47      * 上一次的索引值
 48      */
 49     private String lastIndex;
 50 
 51     /**
 52      * 文件的絕對路徑
 53      */
 54     private String filePath = "";
 55 
 56     /**
 57      * 工做表索引
 58      */
 59     private int sheetIndex = 0;
 60 
 61     /**
 62      * sheet名
 63      */
 64     private String sheetName = "";
 65 
 66     /**
 67      * 總行數
 68      */
 69     private int totalRows=0;
 70 
 71     /**
 72      * 一行內cell集合
 73      */
 74     private List<String> cellList = new ArrayList<String>();
 75 
 76     /**
 77      * 判斷整行是否爲空行的標記
 78      */
 79     private boolean flag = false;
 80 
 81     /**
 82      * 當前行
 83      */
 84     private int curRow = 1;
 85 
 86     /**
 87      * 當前列
 88      */
 89     private int curCol = 0;
 90 
 91     /**
 92      * T元素標識
 93      */
 94     private boolean isTElement;
 95 
 96     /**
 97      * 異常信息,若是爲空則表示沒有異常
 98      */
 99     private String exceptionMessage;
100 
101     /**
102      * 單元格數據類型,默認爲字符串類型
103      */
104     private CellDataType nextDataType = CellDataType.SSTINDEX;
105 
106     private final DataFormatter formatter = new DataFormatter();
107 
108     /**
109      * 單元格日期格式的索引
110      */
111     private short formatIndex;
112 
113     /**
114      * 日期格式字符串
115      */
116     private String formatString;
117 
118     //定義前一個元素和當前元素的位置,用來計算其中空的單元格數量,如A6和A8等
119     private String preRef = null, ref = null;
120 
121     //定義該文檔一行最大的單元格數,用來補全一行最後可能缺失的單元格
122     private String maxRef = null;
123 
124     /**
125      * 單元格
126      */
127     private StylesTable stylesTable;
128 
129     /**
130      * 遍歷工做簿中全部的電子表格
131      * 並緩存在mySheetList中
132      *
133      * @param filename
134      * @throws Exception
135      */
136     public int process(String filename) throws Exception {
137         filePath = filename;
138         OPCPackage pkg = OPCPackage.open(filename);
139         XSSFReader xssfReader = new XSSFReader(pkg);
140         stylesTable = xssfReader.getStylesTable();
141         SharedStringsTable sst = xssfReader.getSharedStringsTable();
142         XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser");
143         this.sst = sst;
144         parser.setContentHandler(this);
145         XSSFReader.SheetIterator sheets = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
146         while (sheets.hasNext()) { //遍歷sheet
147             curRow = 1; //標記初始行爲第一行
148             sheetIndex++;
149             InputStream sheet = sheets.next(); //sheets.next()和sheets.getSheetName()不能換位置,不然sheetName報錯
150             sheetName = sheets.getSheetName();
151             InputSource sheetSource = new InputSource(sheet);
152             parser.parse(sheetSource); //解析excel的每條記錄,在這個過程當中startElement()、characters()、endElement()這三個函數會依次執行
153             sheet.close();
154         }
155         return totalRows; //返回該excel文件的總行數,不包括首列和空行
156     }
157 
158     /**
159      * 第一個執行
160      *
161      * @param uri
162      * @param localName
163      * @param name
164      * @param attributes
165      * @throws SAXException
166      */
167     @Override
168     public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException {
169         //c => 單元格
170         if ("c".equals(name)) {
171             //前一個單元格的位置
172             if (preRef == null) {
173                 preRef = attributes.getValue("r");
174             } else {
175                 preRef = ref;
176             }
177 
178             //當前單元格的位置
179             ref = attributes.getValue("r");
180             //設定單元格類型
181             this.setNextDataType(attributes);
182         }
183 
184         //當元素爲t時
185         if ("t".equals(name)) {
186             isTElement = true;
187         } else {
188             isTElement = false;
189         }
190 
191         //置空
192         lastIndex = "";
193     }
194 
195     /**
196      * 第二個執行
197      * 獲得單元格對應的索引值或是內容值
198      * 若是單元格類型是字符串、INLINESTR、數字、日期,lastIndex則是索引值
199      * 若是單元格類型是布爾值、錯誤、公式,lastIndex則是內容值
200      * @param ch
201      * @param start
202      * @param length
203      * @throws SAXException
204      */
205     @Override
206     public void characters(char[] ch, int start, int length) throws SAXException {
207         lastIndex += new String(ch, start, length);
208     }
209 
210     /**
211      * 第三個執行
212      *
213      * @param uri
214      * @param localName
215      * @param name
216      * @throws SAXException
217      */
218     @Override
219     public void endElement(String uri, String localName, String name) throws SAXException {
220 
221         //t元素也包含字符串
222         if (isTElement) {//這個程序沒通過
223             //將單元格內容加入rowlist中,在這以前先去掉字符串先後的空白符
224             String value = lastIndex.trim();
225             cellList.add(curCol, value);
226             curCol++;
227             isTElement = false;
228             //若是裏面某個單元格含有值,則標識該行不爲空行
229             if (value != null && !"".equals(value)) {
230                 flag = true;
231             }
232         } else if ("v".equals(name)) {
233             //v => 單元格的值,若是單元格是字符串,則v標籤的值爲該字符串在SST中的索引
234             String value = this.getDataValue(lastIndex.trim(), "");//根據索引值獲取對應的單元格值
235             //補全單元格之間的空單元格
236             if (!ref.equals(preRef)) {
237                 int len = countNullCell(ref, preRef);
238                 for (int i = 0; i < len; i++) {
239                     cellList.add(curCol, "");
240                     curCol++;
241                 }
242             }
243             cellList.add(curCol, value);
244             curCol++;
245             //若是裏面某個單元格含有值,則標識該行不爲空行
246             if (value != null && !"".equals(value)) {
247                 flag = true;
248             }
249         } else {
250             //若是標籤名稱爲row,這說明已到行尾,調用optRows()方法
251             if ("row".equals(name)) {
252                 //默認第一行爲表頭,以該行單元格數目爲最大數目
253                 if (curRow == 1) {
254                     maxRef = ref;
255                 }
256                 //補全一行尾部可能缺失的單元格
257                 if (maxRef != null) {
258                     int len = countNullCell(maxRef, ref);
259                     for (int i = 0; i <= len; i++) {
260                         cellList.add(curCol, "");
261                         curCol++;
262                     }
263                 }
264 
265                 if (flag&&curRow!=1){ //該行不爲空行且該行不是第一行,則發送(第一行爲列名,不須要)
266                     ExcelReaderUtil.sendRows(filePath, sheetName, sheetIndex, curRow, cellList);
267                     totalRows++;
268                 }
269 
270                 cellList.clear();
271                 curRow++;
272                 curCol = 0;
273                 preRef = null;
274                 ref = null;
275                 flag=false;
276             }
277         }
278     }
279 
280     /**
281      * 處理數據類型
282      *
283      * @param attributes
284      */
285     public void setNextDataType(Attributes attributes) {
286         nextDataType = CellDataType.NUMBER; //cellType爲空,則表示該單元格類型爲數字
287         formatIndex = -1;
288         formatString = null;
289         String cellType = attributes.getValue("t"); //單元格類型
290         String cellStyleStr = attributes.getValue("s"); //
291         String columnData = attributes.getValue("r"); //獲取單元格的位置,如A1,B1
292 
293         if ("b".equals(cellType)) { //處理布爾值
294             nextDataType = CellDataType.BOOL;
295         } else if ("e".equals(cellType)) {  //處理錯誤
296             nextDataType = CellDataType.ERROR;
297         } else if ("inlineStr".equals(cellType)) {
298             nextDataType = CellDataType.INLINESTR;
299         } else if ("s".equals(cellType)) { //處理字符串
300             nextDataType = CellDataType.SSTINDEX;
301         } else if ("str".equals(cellType)) {
302             nextDataType = CellDataType.FORMULA;
303         }
304 
305         if (cellStyleStr != null) { //處理日期
306             int styleIndex = Integer.parseInt(cellStyleStr);
307             XSSFCellStyle style = stylesTable.getStyleAt(styleIndex);
308             formatIndex = style.getDataFormat();
309             formatString = style.getDataFormatString();
310 
311             if (formatString.contains("m/d/yy")) {
312                 nextDataType = CellDataType.DATE;
313                 formatString = "yyyy-MM-dd hh:mm:ss";
314             }
315 
316             if (formatString == null) {
317                 nextDataType = CellDataType.NULL;
318                 formatString = BuiltinFormats.getBuiltinFormat(formatIndex);
319             }
320         }
321     }
322 
323     /**
324      * 對解析出來的數據進行類型處理
325      * @param value   單元格的值,
326      *                value表明解析:BOOL的爲0或1, ERROR的爲內容值,FORMULA的爲內容值,INLINESTR的爲索引值需轉換爲內容值,
327      *                SSTINDEX的爲索引值需轉換爲內容值, NUMBER爲內容值,DATE爲內容值
328      * @param thisStr 一個空字符串
329      * @return
330      */
331     @SuppressWarnings("deprecation")
332     public String getDataValue(String value, String thisStr) {
333         switch (nextDataType) {
334             // 這幾個的順序不能隨便交換,交換了極可能會致使數據錯誤
335             case BOOL: //布爾值
336                 char first = value.charAt(0);
337                 thisStr = first == '0' ? "FALSE" : "TRUE";
338                 break;
339             case ERROR: //錯誤
340                 thisStr = "\"ERROR:" + value.toString() + '"';
341                 break;
342             case FORMULA: //公式
343                 thisStr = '"' + value.toString() + '"';
344                 break;
345             case INLINESTR:
346                 XSSFRichTextString rtsi = new XSSFRichTextString(value.toString());
347                 thisStr = rtsi.toString();
348                 rtsi = null;
349                 break;
350             case SSTINDEX: //字符串
351                 String sstIndex = value.toString();
352                 try {
353                     int idx = Integer.parseInt(sstIndex);
354                     XSSFRichTextString rtss = new XSSFRichTextString(sst.getEntryAt(idx));//根據idx索引值獲取內容值
355                     thisStr = rtss.toString();
356                     rtss = null;
357                 } catch (NumberFormatException ex) {
358                     thisStr = value.toString();
359                 }
360                 break;
361             case NUMBER: //數字
362                 if (formatString != null) {
363                     thisStr = formatter.formatRawCellContents(Double.parseDouble(value), formatIndex, formatString).trim();
364                 } else {
365                     thisStr = value;
366                 }
367                 thisStr = thisStr.replace("_", "").trim();
368                 break;
369             case DATE: //日期
370                 thisStr = formatter.formatRawCellContents(Double.parseDouble(value), formatIndex, formatString);
371                 // 對日期字符串做特殊處理,去掉T
372                 thisStr = thisStr.replace("T", " ");
373                 break;
374             default:
375                 thisStr = " ";
376                 break;
377         }
378         return thisStr;
379     }
380 
381     public int countNullCell(String ref, String preRef) {
382         //excel2007最大行數是1048576,最大列數是16384,最後一列列名是XFD
383         String xfd = ref.replaceAll("\\d+", "");
384         String xfd_1 = preRef.replaceAll("\\d+", "");
385 
386         xfd = fillChar(xfd, 3, '@', true);
387         xfd_1 = fillChar(xfd_1, 3, '@', true);
388 
389         char[] letter = xfd.toCharArray();
390         char[] letter_1 = xfd_1.toCharArray();
391         int res = (letter[0] - letter_1[0]) * 26 * 26 + (letter[1] - letter_1[1]) * 26 + (letter[2] - letter_1[2]);
392         return res - 1;
393     }
394 
395     public String fillChar(String str, int len, char let, boolean isPre) {
396         int len_1 = str.length();
397         if (len_1 < len) {
398             if (isPre) {
399                 for (int i = 0; i < (len - len_1); i++) {
400                     str = let + str;
401                 }
402             } else {
403                 for (int i = 0; i < (len - len_1); i++) {
404                     str = str + let;
405                 }
406             }
407         }
408         return str;
409     }
410 
411     /**
412      * @return the exceptionMessage
413      */
414     public String getExceptionMessage() {
415         return exceptionMessage;
416     }
417 }
複製代碼

2.2.3 POI經過繼承HSSFListener類來解決Excel2003文件

 解決思路:重寫process(),processRecord()兩個方法,其中processRecord是核心方法,用於處理sheetName和各類單元格數字類型。緩存

複製代碼
  1 package org.poi;
  2 
  3 import org.apache.poi.hssf.eventusermodel.*;
  4 import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord;
  5 import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord;
  6 import org.apache.poi.hssf.model.HSSFFormulaParser;
  7 import org.apache.poi.hssf.record.*;
  8 import org.apache.poi.hssf.usermodel.HSSFDataFormatter;
  9 import org.apache.poi.hssf.usermodel.HSSFWorkbook;
 10 import org.apache.poi.poifs.filesystem.POIFSFileSystem;
 11 
 12 import java.io.FileInputStream;
 13 import java.util.ArrayList;
 14 import java.util.List;
 15 
 16 /**
 17  * @author y
 18  * @create 2018-01-19 14:18
 19  * @desc 用於解決.xls2003版本大數據量問題
 20  **/
 21 public class ExcelXlsReader implements HSSFListener {
 22 
 23     private int minColums = -1;
 24 
 25     private POIFSFileSystem fs;
 26 
 27     /**
 28      * 總行數
 29      */
 30     private int totalRows=0;
 31 
 32     /**
 33      * 上一行row的序號
 34      */
 35     private int lastRowNumber;
 36 
 37     /**
 38      * 上一單元格的序號
 39      */
 40     private int lastColumnNumber;
 41 
 42     /**
 43      * 是否輸出formula,仍是它對應的值
 44      */
 45     private boolean outputFormulaValues = true;
 46 
 47     /**
 48      * 用於轉換formulas
 49      */
 50     private EventWorkbookBuilder.SheetRecordCollectingListener workbookBuildingListener;
 51 
 52     //excel2003工做簿
 53     private HSSFWorkbook stubWorkbook;
 54 
 55     private SSTRecord sstRecord;
 56 
 57     private FormatTrackingHSSFListener formatListener;
 58 
 59     private final HSSFDataFormatter formatter = new HSSFDataFormatter();
 60 
 61     /**
 62      * 文件的絕對路徑
 63      */
 64     private String filePath = "";
 65 
 66     //表索引
 67     private int sheetIndex = 0;
 68 
 69     private BoundSheetRecord[] orderedBSRs;
 70 
 71     @SuppressWarnings("unchecked")
 72     private ArrayList boundSheetRecords = new ArrayList();
 73 
 74     private int nextRow;
 75 
 76     private int nextColumn;
 77 
 78     private boolean outputNextStringRecord;
 79 
 80     //當前行
 81     private int curRow = 0;
 82 
 83     //存儲一行記錄全部單元格的容器
 84     private List<String> cellList = new ArrayList<String>();
 85 
 86     /**
 87      * 判斷整行是否爲空行的標記
 88      */
 89     private boolean flag = false;
 90 
 91     @SuppressWarnings("unused")
 92     private String sheetName;
 93 
 94     /**
 95      * 遍歷excel下全部的sheet
 96      *
 97      * @param fileName
 98      * @throws Exception
 99      */
100     public int process(String fileName) throws Exception {
101         filePath = fileName;
102         this.fs = new POIFSFileSystem(new FileInputStream(fileName));
103         MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this);
104         formatListener = new FormatTrackingHSSFListener(listener);
105         HSSFEventFactory factory = new HSSFEventFactory();
106         HSSFRequest request = new HSSFRequest();
107         if (outputFormulaValues) {
108             request.addListenerForAllRecords(formatListener);
109         } else {
110             workbookBuildingListener = new EventWorkbookBuilder.SheetRecordCollectingListener(formatListener);
111             request.addListenerForAllRecords(workbookBuildingListener);
112         }
113         factory.processWorkbookEvents(request, fs);
114 
115         return totalRows; //返回該excel文件的總行數,不包括首列和空行
116     }
117     
118     /**
119      * HSSFListener 監聽方法,處理Record
120      * 處理每一個單元格
121      * @param record
122      */
123     @SuppressWarnings("unchecked")
124     public void processRecord(Record record) {
125         int thisRow = -1;
126         int thisColumn = -1;
127         String thisStr = null;
128         String value = null;
129         switch (record.getSid()) {
130             case BoundSheetRecord.sid:
131                 boundSheetRecords.add(record);
132                 break;
133             case BOFRecord.sid: //開始處理每一個sheet
134                 BOFRecord br = (BOFRecord) record;
135                 if (br.getType() == BOFRecord.TYPE_WORKSHEET) {
136                     //若是有須要,則創建子工做簿
137                     if (workbookBuildingListener != null && stubWorkbook == null) {
138                         stubWorkbook = workbookBuildingListener.getStubHSSFWorkbook();
139                     }
140 
141                     if (orderedBSRs == null) {
142                         orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
143                     }
144                     sheetName = orderedBSRs[sheetIndex].getSheetname();
145                     sheetIndex++;
146                 }
147                 break;
148             case SSTRecord.sid:
149                 sstRecord = (SSTRecord) record;
150                 break;
151             case BlankRecord.sid: //單元格爲空白
152                 BlankRecord brec = (BlankRecord) record;
153                 thisRow = brec.getRow();
154                 thisColumn = brec.getColumn();
155                 thisStr = "";
156                 cellList.add(thisColumn, thisStr);
157                 break;
158             case BoolErrRecord.sid: //單元格爲布爾類型
159                 BoolErrRecord berec = (BoolErrRecord) record;
160                 thisRow = berec.getRow();
161                 thisColumn = berec.getColumn();
162                 thisStr = berec.getBooleanValue() + "";
163                 cellList.add(thisColumn, thisStr);
164                 checkRowIsNull(thisStr);  //若是裏面某個單元格含有值,則標識該行不爲空行
165                 break;
166             case FormulaRecord.sid://單元格爲公式類型
167                 FormulaRecord frec = (FormulaRecord) record;
168                 thisRow = frec.getRow();
169                 thisColumn = frec.getColumn();
170                 if (outputFormulaValues) {
171                     if (Double.isNaN(frec.getValue())) {
172                         outputNextStringRecord = true;
173                         nextRow = frec.getRow();
174                         nextColumn = frec.getColumn();
175                     } else {
176                         thisStr = '"' + HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
177                     }
178                 } else {
179                     thisStr = '"' + HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
180                 }
181                 cellList.add(thisColumn, thisStr);
182                 checkRowIsNull(thisStr);  //若是裏面某個單元格含有值,則標識該行不爲空行
183                 break;
184             case StringRecord.sid: //單元格中公式的字符串
185                 if (outputNextStringRecord) {
186                     StringRecord srec = (StringRecord) record;
187                     thisStr = srec.getString();
188                     thisRow = nextRow;
189                     thisColumn = nextColumn;
190                     outputNextStringRecord = false;
191                 }
192                 break;
193             case LabelRecord.sid:
194                 LabelRecord lrec = (LabelRecord) record;
195                 curRow = thisRow = lrec.getRow();
196                 thisColumn = lrec.getColumn();
197                 value = lrec.getValue().trim();
198                 value = value.equals("") ? "" : value;
199                 cellList.add(thisColumn, value);
200                 checkRowIsNull(value);  //若是裏面某個單元格含有值,則標識該行不爲空行
201                 break;
202             case LabelSSTRecord.sid: //單元格爲字符串類型
203                 LabelSSTRecord lsrec = (LabelSSTRecord) record;
204                 curRow = thisRow = lsrec.getRow();
205                 thisColumn = lsrec.getColumn();
206                 if (sstRecord == null) {
207                     cellList.add(thisColumn, "");
208                 } else {
209                     value = sstRecord.getString(lsrec.getSSTIndex()).toString().trim();
210                     value = value.equals("") ? "" : value;
211                     cellList.add(thisColumn, value);
212                     checkRowIsNull(value);  //若是裏面某個單元格含有值,則標識該行不爲空行
213                 }
214                 break;
215             case NumberRecord.sid: //單元格爲數字類型
216                 NumberRecord numrec = (NumberRecord) record;
217                 curRow = thisRow = numrec.getRow();
218                 thisColumn = numrec.getColumn();
219 
220                 //第一種方式
221                 //value = formatListener.formatNumberDateCell(numrec).trim();//這個被寫死,採用的m/d/yy h:mm格式,不符合要求
222 
223                 //第二種方式,參照formatNumberDateCell裏面的實現方法編寫
224                 Double valueDouble=((NumberRecord)numrec).getValue();
225                 String formatString=formatListener.getFormatString(numrec);
226                 if (formatString.contains("m/d/yy")){
227                     formatString="yyyy-MM-dd hh:mm:ss";
228                 }
229                 int formatIndex=formatListener.getFormatIndex(numrec);
230                 value=formatter.formatRawCellContents(valueDouble, formatIndex, formatString).trim();
231 
232                 value = value.equals("") ? "" : value;
233                 //向容器加入列值
234                 cellList.add(thisColumn, value);
235                 checkRowIsNull(value);  //若是裏面某個單元格含有值,則標識該行不爲空行
236                 break;
237             default:
238                 break;
239         }
240 
241         //遇到新行的操做
242         if (thisRow != -1 && thisRow != lastRowNumber) {
243             lastColumnNumber = -1;
244         }
245 
246         //空值的操做
247         if (record instanceof MissingCellDummyRecord) {
248             MissingCellDummyRecord mc = (MissingCellDummyRecord) record;
249             curRow = thisRow = mc.getRow();
250             thisColumn = mc.getColumn();
251             cellList.add(thisColumn, "");
252         }
253 
254         //更新行和列的值
255         if (thisRow > -1)
256             lastRowNumber = thisRow;
257         if (thisColumn > -1)
258             lastColumnNumber = thisColumn;
259 
260         //行結束時的操做
261         if (record instanceof LastCellOfRowDummyRecord) {
262             if (minColums > 0) {
263                 //列值從新置空
264                 if (lastColumnNumber == -1) {
265                     lastColumnNumber = 0;
266                 }
267             }
268             lastColumnNumber = -1;
269 
270             if (flag&&curRow!=0) { //該行不爲空行且該行不是第一行,發送(第一行爲列名,不須要)
271                 ExcelReaderUtil.sendRows(filePath, sheetName, sheetIndex, curRow + 1, cellList); //每行結束時,調用sendRows()方法
272                 totalRows++;
273             }
274             //清空容器
275             cellList.clear();
276             flag=false;
277         }
278     }
279 
280     /**
281      * 若是裏面某個單元格含有值,則標識該行不爲空行
282      * @param value
283      */
284     public void checkRowIsNull(String value){
285         if (value != null && !"".equals(value)) {
286             flag = true;
287         }
288     }
289 }
複製代碼

2.2.4 輔助類ExcelReaderUtil

調用ExcelXlsReader類和ExcelXlsxReader類對excel2003和excel2007兩個版本進行大批量數據讀取:app

複製代碼
 1 package org.poi;
 2 
 3 import java.util.List;
 4 
 5 /**
 6  * @author y
 7  * @create 2018-01-19 0:13
 8  * @desc
 9  **/
10 public class ExcelReaderUtil {
11     //excel2003擴展名
12     public static final String EXCEL03_EXTENSION = ".xls";
13     //excel2007擴展名
14     public static final String EXCEL07_EXTENSION = ".xlsx";
15 
16     /**
17      * 每獲取一條記錄,即打印
18      * 在flume裏每獲取一條記錄即發送,而沒必要緩存起來,能夠大大減小內存的消耗,這裏主要是針對flume讀取大數據量excel來講的
19      * @param sheetName
20      * @param sheetIndex
21      * @param curRow
22      * @param cellList
23      */
24     public static void sendRows(String filePath, String sheetName, int sheetIndex, int curRow, List<String> cellList) {
25             StringBuffer oneLineSb = new StringBuffer();
26             oneLineSb.append(filePath);
27             oneLineSb.append("--");
28             oneLineSb.append("sheet" + sheetIndex);
29             oneLineSb.append("::" + sheetName);//加上sheet名
30             oneLineSb.append("--");
31             oneLineSb.append("row" + curRow);
32             oneLineSb.append("::");
33             for (String cell : cellList) {
34                 oneLineSb.append(cell.trim());
35                 oneLineSb.append("|");
36             }
37             String oneLine = oneLineSb.toString();
38             if (oneLine.endsWith("|")) {
39                 oneLine = oneLine.substring(0, oneLine.lastIndexOf("|"));
40             }// 去除最後一個分隔符
41 
42             System.out.println(oneLine);
43     }
44 
45     public static void readExcel(String fileName) throws Exception {
46         int totalRows =0;
47         if (fileName.endsWith(EXCEL03_EXTENSION)) { //處理excel2003文件
48             ExcelXlsReader excelXls=new ExcelXlsReader();
49             totalRows =excelXls.process(fileName);
50         } else if (fileName.endsWith(EXCEL07_EXTENSION)) {//處理excel2007文件
51             ExcelXlsxReader excelXlsxReader = new ExcelXlsxReader();
52             totalRows = excelXlsxReader.process(fileName);
53         } else {
54             throw new Exception("文件格式錯誤,fileName的擴展名只能是xls或xlsx。");
55         }
56         System.out.println("發送的總行數:" + totalRows);
57     }
58 
59     public static void main(String[] args) throws Exception {
60         String path="C:\\Users\\y****\\Desktop\\TestSample\\H_20171226_***_*****_0430.xlsx";
61         ExcelReaderUtil.readExcel(path);
62     }
63 }
複製代碼

github地址xss

https://github.com/SwordfallYeung/POIExcelmaven

3. 參考資料:

http://www.javashuo.com/article/p-afpuzgfg-z.html

http://www.javashuo.com/article/p-wfzamxgg-y.html

http://blog.csdn.net/lishengbo/article/details/40711769

http://www.javashuo.com/article/p-suzhtepl-de.html

http://blog.csdn.net/lipinganq/article/details/78775195

http://blog.csdn.net/lipinganq/article/details/53389501

http://blog.csdn.net/zmx729618/article/details/72639037

http://blog.csdn.net/daiyutage/article/details/53010491

轉載:http://www.javashuo.com/article/p-vskdnsxh-z.html

相關文章
相關標籤/搜索