本文共 4044 字,大约阅读时间需要 13 分钟。
Excel2003与Excel2007在文件格式和存储方式上存在显著差异:
对于大数据量的Xlsx文件,POI提供了SXSSFSXSSFWorkbook类,采用缓存方式进行大批量写入操作。具体实现可以参考POI官网提供的示例。
POI读取Excel文件有两种模式:用户模式和事件驱动模式(SAX模式)。用户模式适合小数据量或常规数据,但在处理大数据量或大量sheet时容易导致内存溢出。POI官方推荐使用SAX事件驱动模式。
确保项目依赖正确的POI版本和相关组件:
4.0.0 POIExcel POIExcel war 1.0-SNAPSHOT POIExcel Maven Webapp http://maven.apache.org junit junit 3.8.1 test org.apache.poi poi 3.17 org.apache.poi poi-ooxml 3.17 org.apache.poi poi-ooxml-schemas 3.17 com.syncthemall boilerpipe 1.2.1 xerces xercesImpl 2.11.0 xml-apis xml-apis 1.4.01 org.apache.xmlbeans xmlbeans 2.6.0 sax sax 2.0.1 org.apache.commons commons-lang3 3.7 POIExcel
通过继承DefaultHandler类,重写process(), startElement(), characters(), endElement()方法,实现对Excel2007文件的解析。
通过继承HSSFListener类,重写processRecord()方法,处理Excel2003文件的解析。
ExcelReaderUtil用于统一处理Excel2003和Excel2007文件的大批量数据读取,支持Flume等数据传输工具的集成。
public class ExcelReaderUtil { public static final String EXCEL03_EXTENSION = ".xls"; public static final String EXCEL07_EXTENSION = ".xlsx"; public static void sendRows(String filePath, String sheetName, int sheetIndex, int curRow, List cellList) { StringBuffer oneLineSb = new StringBuffer(); oneLineSb.append(filePath).append("--").append("sheet").append(sheetIndex).append("--").append(sheetName).append("--").append("row").append(curRow); for (String cell : cellList) { oneLineSb.append(cell.trim()).append("|"); } String oneLine = oneLineSb.toString(); if (oneLine.endsWith("|")) { oneLine = oneLine.substring(0, oneLine.lastIndexOf("|")); } System.out.println(oneLine); } public static void readExcel(String fileName) throws Exception { int totalRows = 0; if (fileName.endsWith(EXCEL03_EXTENSION)) { ExcelXlsReader excelXls = new ExcelXlsReader(); totalRows = excelXls.process(fileName); } else if (fileName.endsWith(EXCEL07_EXTENSION)) { ExcelXlsxReader excelXlsxReader = new ExcelXlsxReader(); totalRows = excelXlsxReader.process(fileName); } else { throw new Exception("文件格式错误,fileName的扩展名只能是xls或xlsx。"); } System.out.println("发送的总行数:" + totalRows); } public static void main(String[] args) throws Exception { String path = "C:\\Users\\y****\\Desktop\\TestSample\\H_20171226_***_*****_0430.xlsx"; ExcelReaderUtil.readExcel(path); }} 转载地址:http://vjqfk.baihongyu.com/