Friday, 9 January 2015

jxl : Get all sheet names in xls file


You can get all sheet names of xls sheet by using getSheetNames() method of Workbook class.

Ex:
Workbook workbook = Workbook.getWorkbook(new File(path));
String[] sheetNames = workbook.getSheetNames();

You can get sample xls sheet here

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 XLSUtils {

    private Workbook workbook = null;

    public XLSUtils(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;
    }

    public String[] getSheetNames(){
        checkWorkbookInitialized();
        return workbook.getSheetNames();
    }
    
}

public class TestUtils {
    public static void main(String[] args) {
        XLSUtils util = new XLSUtils("D:\\data.xls");
        String sheetNames[] = util.getSheetNames();

        for(String s : sheetNames){
            System.out.println(s);
        }
        
        util.closeWorkbook();
    }
}


Output
employee
books
products

Prevoius                                                 Next                                                 Home

No comments:

Post a Comment