HSSFListenerによるExcelファイルの読み込み(2)
// create a new org.apache.poi.poifs.filesystem.Filesystem POIFSFileSystem poifs = new POIFSFileSystem(new FileInputStream("hoge")); // get the Workbook (excel part) stream in a InputStream InputStream din = poifs.createDocumentInputStream("Workbook"); // construct out HSSFRequest object HSSFRequest req = new HSSFRequest(); // lazy listen for ALL records with the listener shown above req.addListenerForAllRecords(HSSFListenerを実装したクラス); // create our event factory HSSFEventFactory factory = new HSSFEventFactory(); // process our events based on the document input stream factory.processEvents(req, din); // once all the events are processed close our file input stream in.close(); // and our document input stream (don't want to leak these!) din.close();
Event APIでは、↑のようにHSSFListenerを実装したクラスをHSSFRequestに登録しておくと、イベントが発生するたびに以下のメソッドが呼び出されます。
public void processRecord(Record record)
セル内のデータの場合には、LabelSSTRecordというクラスが渡されるのですが、空のセルについては、processRecord()が呼び出されず困っていました。
その後、ちゃんと調べてみたら、LabelSSTRecordはgetRow(),getColumn()で、セルの位置がわかるので、データのあるセルだけを処理すれば問題なかったです。1行のセル数については、processRecord()でRowRecordが渡されたときにgetFirstCol(),getLastCol()で取得することができました。