Sunday, September 19, 2010

Reading excel file in java with JXL api

We can use JXL api to read/write/edit an excel file. Here in this article we are going to see how to read an excel file using this api.

First of all you have to download the api and add the path of jxl.jar into the system classpath .

Then the simple following code will read all the cell values from the excel file and will print into the console.

import java.io.*;
import java.util.Scanner;

import jxl.Cell;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class ReadExcel {
    // method that read the excel file and print all it's cell values
    public void readFile(File file) {
        try {
            Workbook wb = Workbook.getWorkbook(file);    // get the excel work book
            // from book you can select sheet and work on it
            // here we are taking the first sheet for our example 
            Sheet sheet = wb.getSheet(0);                
            
            // travel all cells in the selected sheet
            for(int i=0; i < sheet.getRows(); i++) {
                for(int j=0; j < sheet.getColumns(); j++) {
                    Cell cell = sheet.getCell(j, i);                        // get a particular cell
                    System.out.print(cell.getContents() + "\t");    // print cell content
                }
                System.out.println();
            }
        } catch (BiffException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    public static void main(String args[]) {
        // read the file path that you want to read from console
        Scanner in = new Scanner(System.in);
        String file = in.nextLine();
        
        // initiate the ReadExcel class and call the method to read the file
        ReadExcel re = new ReadExcel();
        re.readFile(new File(file));
    }

}


If you need more information regarding this you may visit this link - http://www.vogella.de/articles/JavaExcel/article.html