Friday, March 7, 2014

Excel Reading using JExcel API

There are so many way to read excel using java.Here we know another good JAVA API to read excel that is JExcel. This API handle .xls(Excel 97) file only it can not handle .xlsx(Excel 2007) file.

Now question is how to use this API to read excel file.

First of all we need to download this API.So we can go to this link and download the latest version(jexcelapi_2_6_12) and extract it.

After extracting , it looks like that










Create a new project from our IDE and add jxl.jar in our project.





Now we write the code as given below:

import java.io.File;
import java.io.IOException;
import jxl.Cell;
import jxl.CellType;
import jxl.Sheet;
import jxl.Workbook;
import jxl.WorkbookSettings;

public class ExcelReadJxl {


    public static void main(String[] args) throws IOException, Exception {
        WorkbookSettings workbookSettings = new WorkbookSettings();
        File file = new File("resources/Test1.xls");
        //set the file location for the .xls file 
        Workbook workbook = Workbook.getWorkbook(file, workbookSettings);
        //create workbook object by the settings

        //getting the first sheet inside excel document       
        Sheet customerSheet = workbook.getSheet(0);
        //start reading Excel document        
       ExcelReadJxl.readSheet(customerSheet);
      
// free the memory by closing workbook
       workbook.close();
    }

    private static void readSheet(Sheet sheet) throws Exception {


        //sheet.getCell(columnIndex,rowIndex)
        //getting all rows inside excel document

        for (int i = 0; i < sheet.getRows(); i++) {
        //start looping over rows
            for (int j = 0; j < sheet.getColumns(); j++) {
                Cell cell = sheet.getCell(j, i);
                CellType type = cell.getType();
                if (type == CellType.LABEL) {
                    System.out.printf(sheet.getCell(j, i).getContents() + "\t");
                } else if (type == CellType.NUMBER) {
                    System.out.printf(sheet.getCell(j, i).getContents() + "\t");
                }
            }
            System.out.printf("\n");
        }
    }
}





No comments:

Post a Comment