兩個版本的最大行數和列數不一樣,2003版最大行數是65536行,最大列數是256列,2007版及之後的版本最大行數是1048576行,最大列數是16384列。html
excel2003是以二進制的方式存儲,這種格式不易被其餘軟件讀取使用;而excel2007採用了基於XML的ooxml開放文檔標準,ooxml使用XML和ZIP技術結合進行文件存儲,XML是一個基於文本的格式,並且ZIP容器支持內容的壓縮,因此其一大優點是能夠大大減少文件的尺寸。java
對於大數據的Xlsx文件的寫入,POI3.8提供了SXSSFSXSSFWorkbook類,採用緩存方式進行大批量寫文件。git
詳情能夠查看poi官網示例:http://poi.apache.org/spreadsheet/how-to.html#sxssf 或 http://blog.csdn.net/daiyutage/article/details/53010491github
POI讀取Excel有兩種模式,一種是用戶模式,一種是SAX事件驅動模式,將xlsx格式的文檔轉換成CSV格式後進行讀取。用戶模式API接口豐富,使用POI的API能夠很容易讀取Excel,但用戶模式消耗的內存很大,當遇到很大sheet、大數據網格,假空行、公式等問題時,很容易致使內存溢出。POI官方推薦解決內存溢出的方式使用CVS格式解析,即SAX事件驅動模式。下面主要是講解如何讀取大批量數據:apache
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>
解決思路:經過繼承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 boolean startElementFlag = true; 100 private boolean endElementFlag = false; 101 private boolean charactersFlag = false; 102 103 /** 104 * 異常信息,若是爲空則表示沒有異常 105 */ 106 private String exceptionMessage; 107 108 /** 109 * 單元格數據類型,默認爲字符串類型 110 */ 111 private CellDataType nextDataType = CellDataType.SSTINDEX; 112 113 private final DataFormatter formatter = new DataFormatter(); 114 115 /** 116 * 單元格日期格式的索引 117 */ 118 private short formatIndex; 119 120 /** 121 * 日期格式字符串 122 */ 123 private String formatString; 124 125 //定義前一個元素和當前元素的位置,用來計算其中空的單元格數量,如A6和A8等 126 private String prePreRef = "A", preRef = null, ref = null; 127 128 //定義該文檔一行最大的單元格數,用來補全一行最後可能缺失的單元格 129 private String maxRef = null; 130 131 /** 132 * 單元格 133 */ 134 private StylesTable stylesTable; 135 136 /** 137 * 遍歷工做簿中全部的電子表格 138 * 並緩存在mySheetList中 139 * 140 * @param filename 141 * @throws Exception 142 */ 143 public int process(String filename) throws Exception { 144 filePath = filename; 145 OPCPackage pkg = OPCPackage.open(filename); 146 XSSFReader xssfReader = new XSSFReader(pkg); 147 stylesTable = xssfReader.getStylesTable(); 148 SharedStringsTable sst = xssfReader.getSharedStringsTable(); 149 XMLReader parser = XMLReaderFactory.createXMLReader("org.apache.xerces.parsers.SAXParser"); 150 this.sst = sst; 151 parser.setContentHandler(this); 152 XSSFReader.SheetIterator sheets = (XSSFReader.SheetIterator) xssfReader.getSheetsData(); 153 while (sheets.hasNext()) { //遍歷sheet 154 curRow = 1; //標記初始行爲第一行 155 sheetIndex++; 156 InputStream sheet = sheets.next(); //sheets.next()和sheets.getSheetName()不能換位置,不然sheetName報錯 157 sheetName = sheets.getSheetName(); 158 InputSource sheetSource = new InputSource(sheet); 159 parser.parse(sheetSource); //解析excel的每條記錄,在這個過程當中startElement()、characters()、endElement()這三個函數會依次執行 160 sheet.close(); 161 } 162 return totalRows; //返回該excel文件的總行數,不包括首列和空行 163 } 164 165 /** 166 * 第一個執行 167 * 168 * @param uri 169 * @param localName 170 * @param name 171 * @param attributes 172 * @throws SAXException 173 */ 174 @Override 175 public void startElement(String uri, String localName, String name, Attributes attributes) throws SAXException { 176 //c => 單元格 177 if ("c".equals(name)) { 178 179 //前一個單元格的位置 180 if (preRef == null) { 181 preRef = attributes.getValue("r"); 182 183 } else { 184 //中部文本空單元格標識 ‘endElementFlag’ 判斷前一次是否爲文本空字符串,true則代表不是文本空字符串,false代表是文本空字符串跳過把空字符串的位置賦予preRef 185 if (endElementFlag){ 186 preRef = ref; 187 } 188 } 189 190 //當前單元格的位置 191 ref = attributes.getValue("r"); 192 //首部文本空單元格標識 ‘startElementFlag’ 判斷前一次,即首部是否爲文本空字符串,true則代表不是文本空字符串,false代表是文本空字符串, 且已知當前格,即第二格帶「B」標誌,則ref賦予preRef 193 if (!startElementFlag && !flag){ //上一個單元格爲文本空單元格,執行下面的,使ref=preRef;flag爲true代表該單元格以前有數據值,即該單元格不是首部空單元格,則跳過 194 // 這裏只有上一個單元格爲文本空單元格,且以前的幾個單元格都沒有值纔會執行 195 preRef = ref; 196 } 197 198 //設定單元格類型 199 this.setNextDataType(attributes); 200 endElementFlag = false; 201 charactersFlag = false; 202 startElementFlag = false; 203 } 204 205 //當元素爲t時 206 if ("t".equals(name)) { 207 isTElement = true; 208 } else { 209 isTElement = false; 210 } 211 212 //置空 213 lastIndex = ""; 214 } 215 216 217 218 /** 219 * 第二個執行 220 * 獲得單元格對應的索引值或是內容值 221 * 若是單元格類型是字符串、INLINESTR、數字、日期,lastIndex則是索引值 222 * 若是單元格類型是布爾值、錯誤、公式,lastIndex則是內容值 223 * @param ch 224 * @param start 225 * @param length 226 * @throws SAXException 227 */ 228 @Override 229 public void characters(char[] ch, int start, int length) throws SAXException { 230 startElementFlag = true; 231 charactersFlag = true; 232 lastIndex += new String(ch, start, length); 233 } 234 235 /** 236 * 第三個執行 237 * 238 * @param uri 239 * @param localName 240 * @param name 241 * @throws SAXException 242 */ 243 @Override 244 public void endElement(String uri, String localName, String name) throws SAXException { 245 //t元素也包含字符串 246 if (isTElement) {//這個程序沒通過 247 //將單元格內容加入rowlist中,在這以前先去掉字符串先後的空白符 248 String value = lastIndex.trim(); 249 cellList.add(curCol, value); 250 endElementFlag = true; 251 curCol++; 252 isTElement = false; 253 //若是裏面某個單元格含有值,則標識該行不爲空行 254 if (value != null && !"".equals(value)) { 255 flag = true; 256 } 257 } else if ("v".equals(name)) { 258 //v => 單元格的值,若是單元格是字符串,則v標籤的值爲該字符串在SST中的索引 259 String value = this.getDataValue(lastIndex.trim(), "");//根據索引值獲取對應的單元格值 260 261 //補全單元格之間的空單元格 262 if (!ref.equals(preRef)) { 263 int len = countNullCell(ref, preRef); 264 for (int i = 0; i < len; i++) { 265 cellList.add(curCol, ""); 266 curCol++; 267 } 268 } else if (ref.equals(preRef)){ //ref等於preRef,且以B或者C...開頭,代表首部爲空格 269 cellList.add(curCol, ""); 270 curCol++; 271 int len = countNullCell(ref, "A"); 272 for (int i = 0; i < len; i++) { 273 cellList.add(curCol, ""); 274 curCol++; 275 } 276 } 277 cellList.add(curCol, value); 278 curCol++; 279 endElementFlag = true; 280 //若是裏面某個單元格含有值,則標識該行不爲空行 281 if (value != null && !"".equals(value)) { 282 flag = true; 283 } 284 } else { 285 //若是標籤名稱爲row,這說明已到行尾,調用optRows()方法 286 if ("row".equals(name)) { 287 //默認第一行爲表頭,以該行單元格數目爲最大數目 288 if (curRow == 1) { 289 maxRef = ref; 290 } 291 //補全一行尾部可能缺失的單元格 292 if (maxRef != null) { 293 int len = -1; 294 //前一單元格,true則不是文本空字符串,false則是文本空字符串 295 if (charactersFlag){ 296 len = countNullCell(maxRef, ref); 297 }else { 298 len = countNullCell(maxRef, preRef); 299 } 300 for (int i = 0; i <= len; i++) { 301 cellList.add(curCol, ""); 302 curCol++; 303 } 304 } 305 306 if (flag&&curRow!=1){ //該行不爲空行且該行不是第一行,則發送(第一行爲列名,不須要) 307 ExcelReaderUtil.sendRows(filePath, sheetName, sheetIndex, curRow, cellList); 308 totalRows++; 309 } 310 311 cellList.clear(); 312 curRow++; 313 curCol = 0; 314 preRef = null; 315 prePreRef = null; 316 ref = null; 317 flag=false; 318 } 319 } 320 } 321 322 /** 323 * 處理數據類型 324 * 325 * @param attributes 326 */ 327 public void setNextDataType(Attributes attributes) { 328 nextDataType = CellDataType.NUMBER; //cellType爲空,則表示該單元格類型爲數字 329 formatIndex = -1; 330 formatString = null; 331 String cellType = attributes.getValue("t"); //單元格類型 332 String cellStyleStr = attributes.getValue("s"); // 333 String columnData = attributes.getValue("r"); //獲取單元格的位置,如A1,B1 334 335 if ("b".equals(cellType)) { //處理布爾值 336 nextDataType = CellDataType.BOOL; 337 } else if ("e".equals(cellType)) { //處理錯誤 338 nextDataType = CellDataType.ERROR; 339 } else if ("inlineStr".equals(cellType)) { 340 nextDataType = CellDataType.INLINESTR; 341 } else if ("s".equals(cellType)) { //處理字符串 342 nextDataType = CellDataType.SSTINDEX; 343 } else if ("str".equals(cellType)) { 344 nextDataType = CellDataType.FORMULA; 345 } 346 347 if (cellStyleStr != null) { //處理日期 348 int styleIndex = Integer.parseInt(cellStyleStr); 349 XSSFCellStyle style = stylesTable.getStyleAt(styleIndex); 350 formatIndex = style.getDataFormat(); 351 formatString = style.getDataFormatString(); 352 if (formatString.contains("m/d/yyyy") || formatString.contains("yyyy/mm/dd")|| formatString.contains("yyyy/m/d") ) { 353 nextDataType = CellDataType.DATE; 354 formatString = "yyyy-MM-dd hh:mm:ss"; 355 } 356 357 if (formatString == null) { 358 nextDataType = CellDataType.NULL; 359 formatString = BuiltinFormats.getBuiltinFormat(formatIndex); 360 } 361 } 362 } 363 364 /** 365 * 對解析出來的數據進行類型處理 366 * @param value 單元格的值, 367 * value表明解析:BOOL的爲0或1, ERROR的爲內容值,FORMULA的爲內容值,INLINESTR的爲索引值需轉換爲內容值, 368 * SSTINDEX的爲索引值需轉換爲內容值, NUMBER爲內容值,DATE爲內容值 369 * @param thisStr 一個空字符串 370 * @return 371 */ 372 @SuppressWarnings("deprecation") 373 public String getDataValue(String value, String thisStr) { 374 switch (nextDataType) { 375 // 這幾個的順序不能隨便交換,交換了極可能會致使數據錯誤 376 case BOOL: //布爾值 377 char first = value.charAt(0); 378 thisStr = first == '0' ? "FALSE" : "TRUE"; 379 break; 380 case ERROR: //錯誤 381 thisStr = "\"ERROR:" + value.toString() + '"'; 382 break; 383 case FORMULA: //公式 384 thisStr = '"' + value.toString() + '"'; 385 break; 386 case INLINESTR: 387 XSSFRichTextString rtsi = new XSSFRichTextString(value.toString()); 388 thisStr = rtsi.toString(); 389 rtsi = null; 390 break; 391 case SSTINDEX: //字符串 392 String sstIndex = value.toString(); 393 try { 394 int idx = Integer.parseInt(sstIndex); 395 XSSFRichTextString rtss = new XSSFRichTextString(sst.getEntryAt(idx));//根據idx索引值獲取內容值 396 thisStr = rtss.toString(); 397 System.out.println(thisStr); 398 //有些字符串是文本格式的,但內容倒是日期 399 400 rtss = null; 401 } catch (NumberFormatException ex) { 402 thisStr = value.toString(); 403 } 404 break; 405 case NUMBER: //數字 406 if (formatString != null) { 407 thisStr = formatter.formatRawCellContents(Double.parseDouble(value), formatIndex, formatString).trim(); 408 } else { 409 thisStr = value; 410 } 411 thisStr = thisStr.replace("_", "").trim(); 412 break; 413 case DATE: //日期 414 thisStr = formatter.formatRawCellContents(Double.parseDouble(value), formatIndex, formatString); 415 // 對日期字符串做特殊處理,去掉T 416 thisStr = thisStr.replace("T", " "); 417 break; 418 default: 419 thisStr = " "; 420 break; 421 } 422 return thisStr; 423 } 424 425 public int countNullCell(String ref, String preRef) { 426 //excel2007最大行數是1048576,最大列數是16384,最後一列列名是XFD 427 String xfd = ref.replaceAll("\\d+", ""); 428 String xfd_1 = preRef.replaceAll("\\d+", ""); 429 430 xfd = fillChar(xfd, 3, '@', true); 431 xfd_1 = fillChar(xfd_1, 3, '@', true); 432 433 char[] letter = xfd.toCharArray(); 434 char[] letter_1 = xfd_1.toCharArray(); 435 int res = (letter[0] - letter_1[0]) * 26 * 26 + (letter[1] - letter_1[1]) * 26 + (letter[2] - letter_1[2]); 436 return res - 1; 437 } 438 439 public String fillChar(String str, int len, char let, boolean isPre) { 440 int len_1 = str.length(); 441 if (len_1 < len) { 442 if (isPre) { 443 for (int i = 0; i < (len - len_1); i++) { 444 str = let + str; 445 } 446 } else { 447 for (int i = 0; i < (len - len_1); i++) { 448 str = str + let; 449 } 450 } 451 } 452 return str; 453 } 454 455 /** 456 * @return the exceptionMessage 457 */ 458 public String getExceptionMessage() { 459 return exceptionMessage; 460 } 461 }
解決思路:重寫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 }
調用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
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