Webdriver Script005 : Read Data from Excel

Hi,

This script will read all the content present in excel file. You can simply use this code just by putting your file location in File Object.

Note : - Reading Excel file requires jxl package to be import.

/*********************************************************************

 Title  : Webdriver Script_005 : Reading Data from Excel
 Author : Gaurav Khanna

 *********************************************************************/

package com.gaurav.webdriver;

import java.io.FileInputStream;
import java.io.IOException;
import org.testng.annotations.Test;
import jxl.Sheet;
import jxl.Workbook;
import jxl.read.biff.BiffException;

public class s005_ReadingDataFromExcel {

    @Test
    public void tests005_ReadingDataFromExcel() throws BiffException,
            IOException {

        // Creating File Object
        FileInputStream f = new FileInputStream(
                "C:\\gk\\code\\selenium\\sample\\sample1.xls");

        // Reading File as WorkBook
        Workbook wb = Workbook.getWorkbook(f);

        // Reading Sheet by Name
        Sheet sheet = wb.getSheet("register");

        int r = sheet.getRows();
        int c = sheet.getColumns();

        // Printing Total Number of Rows and Coloumns
        System.out.println("Total Rows : " + r);
        System.out.println("Total Coloumns : " + c);

        for (int rows = 0; rows < sheet.getRows(); rows++) {
            for (int cols = 0; cols < sheet.getColumns(); cols++) {
                // Print all the Values present in Excel Sheet
                System.out.println("(" + rows + "," + cols + ") : "
                        + sheet.getCell(cols, rows).getContents() + "\t");
            }
        }
    }
}
You can download the script from Free Books and Scripts page.