Google Search

Sunday, February 23, 2014

Sample Code to Read data from Excel File !

Below is the sample code to read data from excel file, which i used for Selenium Automation (Selenium WebDriver)

// Code Starts here //

package mentor.qa.selenium;

import java.io.*;

import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;


public class ExcelRead {

public static void main (String args[]) throws Exception {

File excel = new File("F:\\Selenium\\data1.xls");
FileInputStream fis = new FileInputStream(excel);


HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet ws = wb.getSheet("Input");

int rowNum = ws.getLastRowNum()+1;
int colNum = ws.getRow(0).getLastCellNum();

String[][] data  = new String[rowNum][colNum];

for (int i = 0 ; i<rowNum; i++){
HSSFRow row = ws.getRow(i);

for (int j=0;j<colNum;j++){
HSSFCell cell = row.getCell(j);
String value = cellToString(cell);
data[i][j] = value;
System.out.println("Value at position [" +i +"] [" +j +"]is " +value) ;

}

// System.out.println("Value at position [" +i +"] is " +data[i][j]) ;
}

}

public static String cellToString(HSSFCell cell) {

int type ;
Object result ;
type = cell.getCellType() ;

switch (type) {

case 0 : // numeric value in Excel
result = cell.getNumericCellValue() ;
  break ;
case 1 : // String Value in Excel
result = cell.getStringCellValue() ;
break ;
default :
throw new RuntimeException("There are no support for this type of cell") ;
}

return result.toString() ;
}
}

No comments:

Post a Comment