Search code examples
javaseleniumexcellibrary

Code to read from excel sheet is not working


I have the following code to read from a test file and print it on console but it's not printing any thing, I don't know how to chech the error its generating. I am using java, selenium, ie 10, win 8.

public class Rowcount {
    public static void main(String[] args) throws BiffException, IOException {
        FileInputStream exo=new FileInputStream("E:\\Test filee.xlsx");
        Workbook wbo=Workbook.getWorkbook(exo);
        Sheet wso=wbo.getSheet(0);
        int lastrownum;
        lastrownum= wso.getRows();
        System.out.println(lastrownum);
    }
}

Solution

  • the following code worked for me:

    import java.io.File;
    import java.io.IOException;
    
    import jxl.Cell;
    import jxl.CellType;
    import jxl.Sheet;
    import jxl.Workbook;
    import jxl.read.biff.BiffException;
    
    public class ReadExcell {
    public static void main(String[] args) {
    ReadExcell.ExcelFile("D:\\rptViewer.xls");
    }
    
    /*
    * Read excel file using j excel file
    */
    public static String ExcelFile(String path){
    StringBuilder excelContent = new StringBuilder();
    
    try
    {
    Workbook workbook = Workbook.getWorkbook(new File(path));
    Sheet sheet = workbook.getSheet(0);
    
    excelContent = new StringBuffer();
    
    for(int rows = 0 ; rows < sheet.getRows() ; rows++){
    StringBuffer row = new StringBuffer();
    for(int colums = 0 ; colums < sheet.getColumns() ;colums++){
      Cell cell = sheet.getCell(colums, rows);
    if(cell.getType() == CellType.LABEL){
    row.append(cell.getContents()+ ",");
    }else
    if(cell.getType() == CellType.NUMBER){
    row.append(cell.getContents()+ ",");
    }
    }
    
    excelContent.append(row.toString());
    System.out.println(row.toString());
    }
    
    } catch (BiffException e) {
    e.printStackTrace();
    } catch (IOException e) {
    e.printStackTrace();
    }    
    
    return excelContent.toString();
    }
    }