You
can access particular sheet in xls file by using name (or) index.
By using index
Workbook
workbook = Workbook.getWorkbook(new File(path));
Sheet
sheet = workbook.getSheet(index);
By using name
Workbook
workbook = workbook.getSheet(name);
public class NoSheetWithGivenNameException extends RuntimeException{ NoSheetWithGivenNameException(String name){ super("No xls sheet with given name " + name); } }
public class SheetIndexOutOfBoundsException extends RuntimeException{ SheetIndexOutOfBoundsException(int index, int actual){ super("looking for sheet : " + (index+1) + " but actual sheets are : " + actual); } }
public class WorkBookNotInitializedException extends RuntimeException{ WorkBookNotInitializedException(){ super("work book is not initialized"); } }
import java.io.File; import java.io.IOException; import jxl.*; import jxl.read.biff.BiffException; public class XSLUtils { private Workbook workbook = null; public XSLUtils(String path){ try { workbook = Workbook.getWorkbook(new File(path)); } catch (IOException ex) { ex.printStackTrace(); } catch (BiffException ex) { ex.printStackTrace(); } } private void checkWorkbookInitialized(){ if(workbook == null) throw new WorkBookNotInitializedException(); } public int getNoOfSheets(){ checkWorkbookInitialized(); return workbook.getNumberOfSheets(); } public void closeWorkbook(){ checkWorkbookInitialized(); workbook.close(); } public Sheet getSheet(int index){ checkWorkbookInitialized(); if(index >= workbook.getNumberOfSheets()) throw new SheetIndexOutOfBoundsException(index, workbook.getNumberOfSheets()); return workbook.getSheet(index); } public Sheet getSheet(String name){ checkWorkbookInitialized(); Sheet sheet = workbook.getSheet(name); if(sheet == null) throw new NoSheetWithGivenNameException(name); return sheet; } }
import jxl.*; public class TestUtils { public static void main(String[] args) { XSLUtils util = new XSLUtils("D:\\data.xls"); System.out.println("Number of sheets in xsl file are " + util.getNoOfSheets()); Sheet sheet1 = util.getSheet(0); Sheet sheet2 = util.getSheet("books"); System.out.println(sheet1.getName()); System.out.println(sheet2.getName()); util.closeWorkbook(); } }
Output
Number of sheets in xsl file are 3 employee books
No comments:
Post a Comment