POI SAX 使用事件驅動解析Excel(03/07)
裡面用到的相關類請檢視: http://www.cnblogs.com/wshsdlau/p/5643862.html
1. Office2007與Office Open XML
在Office 2007之前,Office一直都是以二進位制位的方式儲存,但這種格式不易被其它軟體拿來使用,在各界的壓力下,MicroSoft於2005年釋出了基於XML的ooxml開放文件標準。ooxml的xml schema強調減少load time,增快parsing speed,將child elements分開儲存,而不是multiple attributes一起存,這有點類似於HTML的結構。ooxml 使用XML和ZIP技術結合進行檔案儲存,因為XML是一個基於文字的格式,而且ZIP容器支援內容的壓縮,所以其一大優勢就是可以大大減小檔案的尺寸。其它特點這裡不再敘述。
2. SAX方式解析XML
SAX全稱Simple API for XML,它是一個介面,也是一個軟體包。它是一種XML解析的替代方法,不同於DOM解析XML文件時把所有內容一次性載入到記憶體中的方式,它逐行掃描文件,一邊掃描,一邊解析。所以那些只需要單遍讀取內容的應用程式就可以從SAX解析中受益,這對大型文件的解析是個巨大優勢。另外,SAX “推" 模型可用於廣播環境,能夠同時註冊多個ContentHandler,並行接收事件,而不是在一個管道中一個接一個地進行處理。一些支援 SAX 的語法分析器包括 Xerces,Apache parser(以前的 IBM 語法分析器)、MSXML(Microsoft 語法分析器)和 XDK(Oracle 語法分析器)。這些語法分析器是最靈活的,因為它們還支援 DOM。
3. POI以SAX解析excel2007檔案
所需jar包:poi-3.10-FINAL-20140208.jar,poi-ooxml-3.10-FINAL-20140208.jar, poi-ooxml-schemas-3.10-FINAL-20140208.jar
xercesImpl.jar xml-apis-2.0.2.jar xmlbeans-2.6.0.jar sax2.jar
輔助類
ExcelReaderUtil:
[java] view plain copy print?- package com.boguan.bte.util.excel;
- import com.boguan.bte.service.common.IExcelRowReader;
- import com.boguan.bte.service.common.impl.ExcelRowReader;
- /**
- * 名稱: ExcelReaderUtil.java<br>
- * 描述: <br>
- * 型別: JAVA<br>
- * 最近修改時間:2016年7月5日 上午10:10:20<br>
- *
- * @since 2016年7月5日
- * @author “”
- */
- publicclass ExcelReaderUtil {
- // excel2003副檔名
- publicstaticfinal String EXCEL03_EXTENSION = ".xls";
- // excel2007副檔名
- publicstaticfinal String EXCEL07_EXTENSION = ".xlsx";
- /**
- * 讀取Excel檔案,可能是03也可能是07版本
- *
- * @param excel03
- * @param excel07
- * @param fileName
- * @throws Exception
- */
- publicstaticvoid readExcel(IExcelRowReader reader, String fileName) throws Exception {
- // 處理excel2003檔案
- if (fileName.endsWith(EXCEL03_EXTENSION)) {
- ExcelXlsReader exceXls = new ExcelXlsReader();
- exceXls.setRowReader(reader);
- exceXls.process(fileName);
- // 處理excel2007檔案
- } elseif (fileName.endsWith(EXCEL07_EXTENSION)) {
- ExcelXlsxReader exceXlsx = new ExcelXlsxReader();
- exceXlsx.setRowReader(reader);
- exceXlsx.process(fileName);
- } else {
- thrownew Exception("檔案格式錯誤,fileName的副檔名只能是xls或xlsx。");
- }
- }
- /**
- * 測試
- * @param args
- * @throws Exception
- */
- publicstaticvoid main(String[] args) throws Exception {
- IExcelRowReader rowReader = new ExcelRowReader();
- ExcelReaderUtil.readExcel(rowReader, "E://test.xls");
- }
- }
package com.boguan.bte.util.excel;
import com.boguan.bte.service.common.IExcelRowReader;
import com.boguan.bte.service.common.impl.ExcelRowReader;
/**
* 名稱: ExcelReaderUtil.java<br>
* 描述: <br>
* 型別: JAVA<br>
* 最近修改時間:2016年7月5日 上午10:10:20<br>
*
* @since 2016年7月5日
* @author “”
*/
public class ExcelReaderUtil {
// excel2003副檔名
public static final String EXCEL03_EXTENSION = ".xls";
// excel2007副檔名
public static final String EXCEL07_EXTENSION = ".xlsx";
/**
* 讀取Excel檔案,可能是03也可能是07版本
*
* @param excel03
* @param excel07
* @param fileName
* @throws Exception
*/
public static void readExcel(IExcelRowReader reader, String fileName) throws Exception {
// 處理excel2003檔案
if (fileName.endsWith(EXCEL03_EXTENSION)) {
ExcelXlsReader exceXls = new ExcelXlsReader();
exceXls.setRowReader(reader);
exceXls.process(fileName);
// 處理excel2007檔案
} else if (fileName.endsWith(EXCEL07_EXTENSION)) {
ExcelXlsxReader exceXlsx = new ExcelXlsxReader();
exceXlsx.setRowReader(reader);
exceXlsx.process(fileName);
} else {
throw new Exception("檔案格式錯誤,fileName的副檔名只能是xls或xlsx。");
}
}
/**
* 測試
* @param args
* @throws Exception
*/
public static void main(String[] args) throws Exception {
IExcelRowReader rowReader = new ExcelRowReader();
ExcelReaderUtil.readExcel(rowReader, "E://test.xls");
}
}
[java] view plain copy print?
- package com.boguan.bte.service.common;
- import java.util.List;
- /**
- * 名稱: IRowReader.java<br>
- * 描述: <br>
- * 型別: JAVA<br>
- * 最近修改時間:2016年7月5日 上午10:28:06<br>
- *
- * @since 2016年7月5日
- * @author “”
- */
- publicinterface IExcelRowReader {
- /**
- * 業務邏輯實現方法
- *
- * @param sheetIndex
- * @param curRow
- * @param rowlist
- */
- void getRows(int sheetIndex, int curRow, List<String> rowlist);
- }
package com.boguan.bte.service.common;
import java.util.List;
/**
* 名稱: IRowReader.java<br>
* 描述: <br>
* 型別: JAVA<br>
* 最近修改時間:2016年7月5日 上午10:28:06<br>
*
* @since 2016年7月5日
* @author “”
*/
public interface IExcelRowReader {
/**
* 業務邏輯實現方法
*
* @param sheetIndex
* @param curRow
* @param rowlist
*/
void getRows(int sheetIndex, int curRow, List<String> rowlist);
}
[java] view plain copy print?
- package com.boguan.bte.service.common.impl;
- import java.util.List;
- import com.boguan.bte.service.common.IExcelRowReader;
- /**
- * 名稱: ExcelRowReader.java<br>
- * 描述: <br>
- * 型別: JAVA<br>
- * 最近修改時間:2016年7月5日 上午10:30:11<br>
- *
- * @since 2016年7月5日
- * @author “”
- */
- publicclass ExcelRowReader implements IExcelRowReader {
- @Override
- publicvoid getRows(int sheetIndex, int curRow, List<String> rowlist) {
- System.out.print(curRow+" ");
- for (int i = 0; i < rowlist.size(); i++) {
- System.out.print(rowlist.get(i)==""?"*":rowlist.get(i) + " ");
- }
- System.out.println();
- }
- }
package com.boguan.bte.service.common.impl;
import java.util.List;
import com.boguan.bte.service.common.IExcelRowReader;
/**
* 名稱: ExcelRowReader.java<br>
* 描述: <br>
* 型別: JAVA<br>
* 最近修改時間:2016年7月5日 上午10:30:11<br>
*
* @since 2016年7月5日
* @author “”
*/
public class ExcelRowReader implements IExcelRowReader {
@Override
public void getRows(int sheetIndex, int curRow, List<String> rowlist) {
System.out.print(curRow+" ");
for (int i = 0; i < rowlist.size(); i++) {
System.out.print(rowlist.get(i)==""?"*":rowlist.get(i) + " ");
}
System.out.println();
}
}
03 Reader:
[java] view plain copy print?- package com.boguan.bte.util.excel;
- import java.io.FileInputStream;
- import java.io.IOException;
- import java.util.ArrayList;
- import java.util.List;
- import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder.SheetRecordCollectingListener;
- import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener;
- import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
- import org.apache.poi.hssf.eventusermodel.HSSFListener;
- import org.apache.poi.hssf.eventusermodel.HSSFRequest;
- import org.apache.poi.hssf.eventusermodel.MissingRecordAwareHSSFListener;
- import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord;
- import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord;
- import org.apache.poi.hssf.model.HSSFFormulaParser;
- import org.apache.poi.hssf.record.BOFRecord;
- import org.apache.poi.hssf.record.BlankRecord;
- import org.apache.poi.hssf.record.BoolErrRecord;
- import org.apache.poi.hssf.record.BoundSheetRecord;
- import org.apache.poi.hssf.record.FormulaRecord;
- import org.apache.poi.hssf.record.LabelRecord;
- import org.apache.poi.hssf.record.LabelSSTRecord;
- import org.apache.poi.hssf.record.NumberRecord;
- import org.apache.poi.hssf.record.Record;
- import org.apache.poi.hssf.record.SSTRecord;
- import org.apache.poi.hssf.record.StringRecord;
- import org.apache.poi.hssf.usermodel.HSSFWorkbook;
- import org.apache.poi.poifs.filesystem.POIFSFileSystem;
- import com.boguan.bte.service.common.IExcelRowReader;
- /**
- * 名稱: ExcelXlsReader.java<br>
- * 描述: <br>
- * 型別: JAVA<br>
- * 最近修改時間:2016年7月5日 上午10:00:32<br>
- *
- * @since 2016年7月5日
- * @author “”
- */
- publicclass ExcelXlsReader implements HSSFListener {
- privateint minColumns = -1;
- private POIFSFileSystem fs;
- privateint lastRowNumber;
- privateint lastColumnNumber;
- /** Should we output the formula, or the value it has? */
- privateboolean outputFormulaValues = true;
- /** For parsing Formulas */
- private SheetRecordCollectingListener workbookBuildingListener;
- // excel2003工作薄
- private HSSFWorkbook stubWorkbook;
- // Records we pick up as we process
- private SSTRecord sstRecord;
- private FormatTrackingHSSFListener formatListener;
- // 表索引
- privateint sheetIndex = -1;
- private BoundSheetRecord[] orderedBSRs;
- @SuppressWarnings("unchecked")
- private ArrayList boundSheetRecords = new ArrayList();
- // For handling formulas with string results
- privateint nextRow;
- privateint nextColumn;
- privateboolean outputNextStringRecord;
- // 當前行
- privateint curRow = 0;
- // 儲存行記錄的容器
- private List<String> rowlist = new ArrayList<String>();;
- @SuppressWarnings("unused")
- private String sheetName;
- private IExcelRowReader rowReader;
- publicvoid setRowReader(IExcelRowReader rowReader) {
- this.rowReader = rowReader;
- }
- /**
- * 遍歷excel下所有的sheet
- *
- * @throws IOException
- */
- publicvoid process(String fileName) throws IOException {
- this.fs = new POIFSFileSystem(new FileInputStream(fileName));
- MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this);
- formatListener = new FormatTrackingHSSFListener(listener);
- HSSFEventFactory factory = new HSSFEventFactory();
- HSSFRequest request = new HSSFRequest();
- if (outputFormulaValues) {
- request.addListenerForAllRecords(formatListener);
- } else {
- workbookBuildingListener = new SheetRecordCollectingListener(formatListener);
- request.addListenerForAllRecords(workbookBuildingListener);
- }
- factory.processWorkbookEvents(request, fs);
- }
- /**
- * HSSFListener 監聽方法,處理 Record
- */
- @SuppressWarnings("unchecked")
- publicvoid processRecord(Record record) {
- int thisRow = -1;
- int thisColumn = -1;
- String thisStr = null;
- String value = null;
- switch (record.getSid()) {
- case BoundSheetRecord.sid:
- boundSheetRecords.add(record);
- break;
- case BOFRecord.sid:
- BOFRecord br = (BOFRecord) record;
- if (br.getType() == BOFRecord.TYPE_WORKSHEET) {
- // 如果有需要,則建立子工作薄
- if (workbookBuildingListener != null && stubWorkbook == null) {
- stubWorkbook = workbookBuildingListener.getStubHSSFWorkbook();
- }
- sheetIndex++;
- if (orderedBSRs == null) {
- orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
- }
- sheetName = orderedBSRs[sheetIndex].getSheetname();
- }
- break;
- case SSTRecord.sid:
- sstRecord = (SSTRecord) record;
- break;
- case BlankRecord.sid:
- BlankRecord brec = (BlankRecord) record;
- thisRow = brec.getRow();
- thisColumn = brec.getColumn();
- thisStr = "";
- rowlist.add(thisColumn, thisStr);
- break;
- case BoolErrRecord.sid: // 單元格為布林型別
- BoolErrRecord berec = (BoolErrRecord) record;
- thisRow = berec.getRow();
- thisColumn = berec.getColumn();
- thisStr = berec.getBooleanValue() + "";
- rowlist.add(thisColumn, thisStr);
- break;
- case FormulaRecord.sid: // 單元格為公式型別
- FormulaRecord frec = (FormulaRecord) record;
- thisRow = frec.getRow();
- thisColumn = frec.getColumn();
- if (outputFormulaValues) {
- if (Double.isNaN(frec.getValue())) {
- // Formula result is a string
- // This is stored in the next record
- outputNextStringRecord = true;
- nextRow = frec.getRow();
- nextColumn = frec.getColumn();
- } else {
- thisStr = formatListener.formatNumberDateCell(frec);
- }
- } else {
- thisStr = '"' + HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
- }
- rowlist.add(thisColumn, thisStr);
- break;
- case StringRecord.sid:// 單元格中公式的字串
- if (outputNextStringRecord) {
- // String for formula
- StringRecord srec = (StringRecord) record;
- thisStr = srec.getString();
- thisRow = nextRow;
- thisColumn = nextColumn;
- outputNextStringRecord = false;
- }
- break;
- case LabelRecord.sid:
- LabelRecord lrec = (LabelRecord) record;
- curRow = thisRow = lrec.getRow();
- thisColumn = lrec.getColumn();
- value = lrec.getValue().trim();
- value = value.equals("") ? " " : value;
- this.rowlist.add(thisColumn, value);
- break;
- case LabelSSTRecord.sid: // 單元格為字串型別
- LabelSSTRecord lsrec = (LabelSSTRecord) record;
- curRow = thisRow = lsrec.getRow();
- thisColumn = lsrec.getColumn();
- if (sstRecord == null) {
- rowlist.add(thisColumn, " ");
- } else {
- value = sstRecord.getString(lsrec.getSSTIndex()).toString().trim();
- value = value.equals("") ? " " : value;
- rowlist.add(thisColumn, value);
- }
- break;
- case NumberRecord.sid: // 單元格為數字型別
- NumberRecord numrec = (NumberRecord) record;
- curRow = thisRow = numrec.getRow();
- thisColumn = numrec.getColumn();
- value = formatListener.formatNumberDateCell(numrec).trim();
- value = value.equals("") ? " " : value;
- // 向容器加入列值
- rowlist.add(thisColumn, value);
- break;
- default:
- break;
- }
- // 遇到新行的操作
- if (thisRow != -1 && thisRow != lastRowNumber) {
- lastColumnNumber = -1;
- }
- // 空值的操作
- if (record instanceof MissingCellDummyRecord) {
- MissingCellDummyRecord mc = (MissingCellDummyRecord) record;
- curRow = thisRow = mc.getRow();
- thisColumn = mc.getColumn();
- rowlist.add(thisColumn, " ");
- }
- // 更新行和列的值
- if (thisRow > -1)
- lastRowNumber = thisRow;
- if (thisColumn > -1)
- lastColumnNumber = thisColumn;
- // 行結束時的操作
- if (record instanceof LastCellOfRowDummyRecord) {
- if (minColumns > 0) {
- // 列值重新置空
- if (lastColumnNumber == -1) {
- lastColumnNumber = 0;
- }
- }
- lastColumnNumber = -1;
- // 每行結束時, 呼叫getRows() 方法
- rowReader.getRows(sheetIndex, curRow, rowlist);
- // 清空容器
- rowlist.clear();
- }
- }
- publicstaticvoid main(String[] args) {
- IExcelRowReader rowReader = new ExcelRowReader();
- try {
- // ExcelReaderUtil.readExcel(rowReader,
- // "E://2016-07-04-011940a.xls");
- System.out.println("**********************************************");
- ExcelReaderUtil.readExcel(rowReader, "E://test.xlsx");
- } catch (Exception e) {
- e.printStackTrace();
- }
- }
- }
package com.boguan.bte.util.excel;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.eventusermodel.EventWorkbookBuilder.SheetRecordCollectingListener;
import org.apache.poi.hssf.eventusermodel.FormatTrackingHSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFEventFactory;
import org.apache.poi.hssf.eventusermodel.HSSFListener;
import org.apache.poi.hssf.eventusermodel.HSSFRequest;
import org.apache.poi.hssf.eventusermodel.MissingRecordAwareHSSFListener;
import org.apache.poi.hssf.eventusermodel.dummyrecord.LastCellOfRowDummyRecord;
import org.apache.poi.hssf.eventusermodel.dummyrecord.MissingCellDummyRecord;
import org.apache.poi.hssf.model.HSSFFormulaParser;
import org.apache.poi.hssf.record.BOFRecord;
import org.apache.poi.hssf.record.BlankRecord;
import org.apache.poi.hssf.record.BoolErrRecord;
import org.apache.poi.hssf.record.BoundSheetRecord;
import org.apache.poi.hssf.record.FormulaRecord;
import org.apache.poi.hssf.record.LabelRecord;
import org.apache.poi.hssf.record.LabelSSTRecord;
import org.apache.poi.hssf.record.NumberRecord;
import org.apache.poi.hssf.record.Record;
import org.apache.poi.hssf.record.SSTRecord;
import org.apache.poi.hssf.record.StringRecord;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.poifs.filesystem.POIFSFileSystem;
import com.boguan.bte.service.common.IExcelRowReader;
/**
* 名稱: ExcelXlsReader.java<br>
* 描述: <br>
* 型別: JAVA<br>
* 最近修改時間:2016年7月5日 上午10:00:32<br>
*
* @since 2016年7月5日
* @author “”
*/
public class ExcelXlsReader implements HSSFListener {
private int minColumns = -1;
private POIFSFileSystem fs;
private int lastRowNumber;
private int lastColumnNumber;
/** Should we output the formula, or the value it has? */
private boolean outputFormulaValues = true;
/** For parsing Formulas */
private SheetRecordCollectingListener workbookBuildingListener;
// excel2003工作薄
private HSSFWorkbook stubWorkbook;
// Records we pick up as we process
private SSTRecord sstRecord;
private FormatTrackingHSSFListener formatListener;
// 表索引
private int sheetIndex = -1;
private BoundSheetRecord[] orderedBSRs;
@SuppressWarnings("unchecked")
private ArrayList boundSheetRecords = new ArrayList();
// For handling formulas with string results
private int nextRow;
private int nextColumn;
private boolean outputNextStringRecord;
// 當前行
private int curRow = 0;
// 儲存行記錄的容器
private List<String> rowlist = new ArrayList<String>();;
@SuppressWarnings("unused")
private String sheetName;
private IExcelRowReader rowReader;
public void setRowReader(IExcelRowReader rowReader) {
this.rowReader = rowReader;
}
/**
* 遍歷excel下所有的sheet
*
* @throws IOException
*/
public void process(String fileName) throws IOException {
this.fs = new POIFSFileSystem(new FileInputStream(fileName));
MissingRecordAwareHSSFListener listener = new MissingRecordAwareHSSFListener(this);
formatListener = new FormatTrackingHSSFListener(listener);
HSSFEventFactory factory = new HSSFEventFactory();
HSSFRequest request = new HSSFRequest();
if (outputFormulaValues) {
request.addListenerForAllRecords(formatListener);
} else {
workbookBuildingListener = new SheetRecordCollectingListener(formatListener);
request.addListenerForAllRecords(workbookBuildingListener);
}
factory.processWorkbookEvents(request, fs);
}
/**
* HSSFListener 監聽方法,處理 Record
*/
@SuppressWarnings("unchecked")
public void processRecord(Record record) {
int thisRow = -1;
int thisColumn = -1;
String thisStr = null;
String value = null;
switch (record.getSid()) {
case BoundSheetRecord.sid:
boundSheetRecords.add(record);
break;
case BOFRecord.sid:
BOFRecord br = (BOFRecord) record;
if (br.getType() == BOFRecord.TYPE_WORKSHEET) {
// 如果有需要,則建立子工作薄
if (workbookBuildingListener != null && stubWorkbook == null) {
stubWorkbook = workbookBuildingListener.getStubHSSFWorkbook();
}
sheetIndex++;
if (orderedBSRs == null) {
orderedBSRs = BoundSheetRecord.orderByBofPosition(boundSheetRecords);
}
sheetName = orderedBSRs[sheetIndex].getSheetname();
}
break;
case SSTRecord.sid:
sstRecord = (SSTRecord) record;
break;
case BlankRecord.sid:
BlankRecord brec = (BlankRecord) record;
thisRow = brec.getRow();
thisColumn = brec.getColumn();
thisStr = "";
rowlist.add(thisColumn, thisStr);
break;
case BoolErrRecord.sid: // 單元格為布林型別
BoolErrRecord berec = (BoolErrRecord) record;
thisRow = berec.getRow();
thisColumn = berec.getColumn();
thisStr = berec.getBooleanValue() + "";
rowlist.add(thisColumn, thisStr);
break;
case FormulaRecord.sid: // 單元格為公式型別
FormulaRecord frec = (FormulaRecord) record;
thisRow = frec.getRow();
thisColumn = frec.getColumn();
if (outputFormulaValues) {
if (Double.isNaN(frec.getValue())) {
// Formula result is a string
// This is stored in the next record
outputNextStringRecord = true;
nextRow = frec.getRow();
nextColumn = frec.getColumn();
} else {
thisStr = formatListener.formatNumberDateCell(frec);
}
} else {
thisStr = '"' + HSSFFormulaParser.toFormulaString(stubWorkbook, frec.getParsedExpression()) + '"';
}
rowlist.add(thisColumn, thisStr);
break;
case StringRecord.sid:// 單元格中公式的字串
if (outputNextStringRecord) {
// String for formula
StringRecord srec = (StringRecord) record;
thisStr = srec.getString();
thisRow = nextRow;
thisColumn = nextColumn;
outputNextStringRecord = false;
}
break;
case LabelRecord.sid:
LabelRecord lrec = (LabelRecord) record;
curRow = thisRow = lrec.getRow();
thisColumn = lrec.getColumn();
value = lrec.getValue().trim();
value = value.equals("") ? " " : value;
this.rowlist.add(thisColumn, value);
break;
case LabelSSTRecord.sid: // 單元格為字串型別
LabelSSTRecord lsrec = (LabelSSTRecord) record;
curRow = thisRow = lsrec.getRow();
thisColumn = lsrec.getColumn();
if (sstRecord == null) {
rowlist.add(thisColumn, " ");
} else {
value = sstRecord.getString(lsrec.getSSTIndex()).toString().trim();
value = value.equals("") ? " " : value;
rowlist.add(thisColumn, value);
}
break;
case NumberRecord.sid: // 單元格為數字型別
NumberRecord numrec = (NumberRecord) record;
curRow = thisRow = numrec.getRow();
thisColumn = numrec.getColumn();
value = formatListener.formatNumberDateCell(numrec).trim();
value = value.equals("") ? " " : value;
// 向容器加入列值
rowlist.add(thisColumn, value);
break;
default:
break;
}
// 遇到新行的操作
if (thisRow != -1 && thisRow != lastRowNumber) {
lastColumnNumber = -1;
}
// 空值的操作
if (record instanceof MissingCellDummyRecord) {
MissingCellDummyRecord mc = (MissingCellDummyRecord) record;
curRow = thisRow = mc.getRow();
thisColumn = mc.getColumn();
rowlist.add(thisColumn, " ");
}
// 更新行和列的值
if (thisRow > -1)
lastRowNumber = thisRow;
if (thisColumn > -1)
lastColumnNumber = thisColumn;
// 行結束時的操作
if (record instanceof LastCellOfRowDummyRecord) {
if (minColumns > 0) {
// 列值重新置空
if (lastColumnNumber == -1) {
lastColumnNumber = 0;
}
}
lastColumnNumber = -1;
// 每行結束時, 呼叫getRows() 方法
rowReader.getRows(sheetIndex, curRow, rowlist);
// 清空容器
rowlist.clear();
}
}
public static void main(String[] args) {
IExcelRowReader rowReader = new ExcelRowReader();
try {
// ExcelReaderUtil.readExcel(rowReader,
// "E://2016-07-04-011940a.xls");
System.out.println("**********************************************");
ExcelReaderUtil.readExcel(rowReader, "E://test.xlsx");
} catch (Exception e) {
e.printStackTrace();
}
}
}
07Reader:
[java] view plain copy print?- package com.boguan.bte.util.excel;
- import java.io.IOException;
- import java.io.InputStream;
- import java.util.ArrayList;
- import java.util.Iterator;
- import java.util.List;
- import org.apache.commons.lang.StringUtils;
- import org.apache.poi.openxml4j.exceptions.OpenXML4JException;
- import org.apache.poi.openxml4j.opc.OPCPackage;
- import org.apache.poi.ss.usermodel.BuiltinFormats;
- import org.apache.poi.ss.usermodel.DataFormatter;
- import org.apache.poi.xssf.eventusermodel.XSSFReader;
- import org.apache.poi.xssf.model.SharedStringsTable;
- import org.apache.poi.xssf.model.StylesTable;
- import org.apache.poi.xssf.usermodel.XSSFCellStyle;
- import org.apache.poi.xssf.usermodel.XSSFRichTextString;
- import org.xml.sax.Attributes;
- import org.xml.sax.InputSource;
- import org.xml.sax.SAXException;
- import org.xml.sax.XMLReader;
- import org.xml.sax.helpers.DefaultHandler;
- import org.xml.sax.helpers.XMLReaderFactory;
- import com.boguan.bte.service.common.IExcelRowReader;
- import com.boguan.bte.service.common.impl.ExcelRowReader;
- /**
- * 名稱: ExcelXlsxReader.java<br>
- * 描述: <br>
- * 型別: JAVA<br>
- * 最近修改時間:2016年7月5日 上午10:00:52<br>
- *
- * @since 2016年7月5日
- * @author “”
- */
- publicclass ExcelXlsxReader extends DefaultHandler {
- private IExcelRowReader rowReader;
- publicvoid setRowReader(IExcelRowReader rowReader) {
- this.rowReader = rowReader;
- }
- /**
- * 共享字串表
- */
- private SharedStringsTable sst;
- /**
- * 上一次的內容
- */
- private String lastContents;
- /**
- * 字串標識
- */
- privateboolean nextIsString;
- /**
- * 工作表索引
- */
- privateint sheetIndex = -1;
- /**
- * 行集合
- */
- private List<String> rowlist = new ArrayList<String>();
- /**
- * 當前行
- */
- privateint curRow = 0;
- /**
- * 當前列
- */
- privateint curCol = 0;
- /**
- * T元素標識
- */
- privateboolean isTElement;
- /**
- * 異常資訊,如果為空則表示沒有異常
- */
- private String exceptionMessage;