POI

POI api Projects

POI api Project 1

Find Name of Excel Sheet
Previous Home Next

In this page of the tutorials we are going to find the name of an excel sheet using POI2.5. by The help of event API we can read XLS with a relatively small memory.

we know that for using to Event of POI we are constructing an instance of org.apache.poi.hssf.eventmodel.HSSFRequest. and for registering a class we have to create listenerorg.apache.poi.hssf.eventmodel.HSSFListener interface and useHSSFRequest.addListener(yourlistener, recordsid) method.

The record sid should be a static reference number (such as BOFRecord.sid) contained in the classes in org.apache.poi.hssf.record.Alternatively we can call HSSFRequest.addListenerForAllRecords(mylistener).

If we can register in listeners in the HSSFRequest object successfully we can construct an instance oforg.apache.poi.poifs.filesystem.FileSystem and pass it our XLS file as inputstream.

We can either pass this, along with the request we constructed, to an instance of HSSFEventFactory via theHSSFEventFactory.processWorkbookEvents(request, Filesystem) method, Once we make this call, the listeners that we constructed receive calls to their processRecord(Record) methods with each Record they are registered to listen for until the file has been completely read.

Methods Description

getSid()

This method is used to give the description about the file copied from class.

getSheetname()

This methods used to find the name of sheet from BoundSheetRecord.

Example

package r4r;
import java.io.*;
import org.apache.poi.hssf.usermodel.*;
import org.apache.poi.poifs.filesystem.*;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.eventusermodel.*;
import org.apache.poi.hssf.record.*;
import org.apache.poi.hssf.dev.EFHSSF;
public class findsheetname implements HSSFListener{
public static void main(String[] args) throws IOException
  {
 FileInputStream fis = new FileInputStream(args[0]);
 POIFSFileSystem pfs = new POIFSFileSystem(fis);
  InputStream in = pfs.createDocumentInputStream("Workbook");
  HSSFRequest hreq = new HSSFRequest();
 hreq.addListenerForAllRecords(new findsheetname());
 HSSFEventFactory fact = new HSSFEventFactory();
  fact.processEvents(hreq, in);
  fis.close();
 in.close();
  System.out.println("STOP");
  }
  public void processRecord(Record record)
  {
  switch (record.getSid())  {
 
  case  BoundSheetRecord.sid:
  BoundSheetRecord bsrecord =
(BoundSheetRecord) record;
 System.out.println("New Name: " +
 bsrecord.getSheetname());
  break;
  } } 
}
Previous Home Next