Tuesday, March 6, 2012

Read Excel and Store Data in Array..

During my Selenium learning period i spend 1 day to get this simple code, i am sharing this with everyone. Simple code for Data Driven Automation which can be used to read each sheet and store in Separate Array which can be accessed anywhere in your Java program. I used POI for this...


1 - From my main class i am calling these lines...
HashMap sheetValues = new HashMap();
InputData.ReadSheet("C:\\TestData.xls","Driver"); // Driver is my sheet name
sheetValues.put("Driver", InputData.getValueArray()); //Read the data here

String driverValueArray[][] = sheetValues.get("Driver");




2 - Class where Excel file i am reading..
package temp;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.Iterator;

import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.*;
//import org.apache.poi.xssf.usermodel.XSSFCell;
//import org.apache.poi.xssf.usermodel.XSSFRow;
//import org.apache.poi.xssf.usermodel.XSSFSheet;
//import org.apache.poi.xssf.usermodel.XSSFWorkbook;


public class InputData {

public static String valueArray[][] = null;
/**
* @throws Exception
*/
public static void ReadSheet(String filename, String sheetName) throws Exception
{
FileInputStream fis = null;
try {
fis = new FileInputStream(filename);
XSSFWorkbook workbook = new XSSFWorkbook(fis);
XSSFSheet sheet = workbook.getSheet(sheetName);
int LastRow=sheet.getLastRowNum();
XSSFRow temprow = sheet.getRow(0);
int lastcol = temprow.getLastCellNum();
valueArray = new String[LastRow+1][lastcol];
Iterator rows = sheet.rowIterator();
int i = 0;
while (rows.hasNext())
{
XSSFRow row = ((XSSFRow) rows.next());
Iterator cells = row.cellIterator();
int j =0;
while(cells.hasNext())
{
XSSFCell cell = (XSSFCell) cells.next();
int type = cell.getCellType();
String value = "";
if(type == Cell.CELL_TYPE_STRING) {
value = cell.getStringCellValue();
} else if(type == Cell.CELL_TYPE_NUMERIC) {
//value = new Double(cell.getNumericCellValue()).toString();
value = cell.getRawValue().toString();
} /*else if(type == Cell.CELL_TYPE_STRING) {
value = new Double(cell.getNumericCellValue()).toString();
//value = cell.getRawValue();
} */
valueArray[i][j] = value;
j++;
}
i++;
}
} catch (IOException e) {
e.printStackTrace();
} finally {
if (fis != null) {
fis.close();
}
}
}
public static void main(String[] args) {
InputData object=new InputData();
try{
ReadSheet("","");
}catch(Exception e)
{
e.printStackTrace();
}
}


public static String[][] getValueArray() {
return valueArray;
}


public static void setValueArray(String[][] valueArray) {
InputData.valueArray = valueArray;
}
}


No comments:

Post a Comment