---Data provider class---
public class TestData {
#DataProvider(name = "data")
public static Object[][] getTableArray() throws Exception {
File src = new File("D:/Data/Data.xlsx");
FileInputStream fis = new FileInputStream(src);//getting error for this line
Workbook wb = new XSSFWorkbook(fis);
Sheet sh = wb.getSheet("Credentials");
int rowcount = sh.getLastRowNum();
String[][] cred = getCellData(sh,rowcount);
System.out.println(cred[0][0]);
return cred;
}
public static String[][] getCellData(Sheet sh, int rowcount){
int ri=0,ci=0;
Cell cell=null;
String data[][]=null;
int colcount = 2;
for( ri=0;ri<=rowcount;ri++){
for (ci=0;ci<colcount;ci++){
cell = sh.getRow(ri).getCell(ci);
data[ri][ci]=cell.getStringCellValue();
}
System.out.println(cell);
}
return data;
}
--Accessing Class----
public class Data {
#Test(dataProvider="data", dataProviderClass = TestData.class )
public void read(String username, String password) {
System.out.println(username);
System.out.println(password);
}
}
This is my code i am getting error on the line where i have added the comment. Error is : java.io.FileNotFoundException: ?D:\Data\Data.xlsx (The filename, directory name, or volume label syntax is incorrect)
Related
The code below prints the content from the excel file (tried in eclipse) but I am not able to run it in Jmeter 3.1 using Groovy.
I throws error:
Problem in JSR223 script JSR223 Sampler, message:
javax.script.ScriptException:
org.codehaus.groovy.control.MultipleCompilationErrorsException:
startup failed
This is my code:
public static void main (String args[]) throws IOException
{
GetExcelTableInto2DArrayListString("C:\\Users\\val1\\Desktop\\Book1.xlsx", true);
}
public static void GetExcelTableInto2DArrayListString(String excelFile, boolean debug) throws IOException{
ArrayList<String> OUT = new ArrayList<String>();
File myFile = new File(excelFile);
FileInputStream fis = null;
fis = new FileInputStream(myFile);
String columnWanted = "PhysicalIDs";
Integer columnNo = null;
XSSFWorkbook myWorkBook = null;
myWorkBook = new XSSFWorkbook (fis);
// Return first sheet from the XLSX workbook
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
// Get iterator to all the rows in current sheet
List<Cell> cells = new ArrayList<Cell>();
Row firstRow = mySheet.getRow(0); //rowIterator.next();
for(Cell cell:firstRow){
if (cell.getStringCellValue().equals(columnWanted)){
columnNo = cell.getColumnIndex();
}
}
System.out.println(columnNo);
DataFormatter formatter = new DataFormatter(Locale.US);
if (columnNo != null){
for (Row row : mySheet) {
Cell c = row.getCell(columnNo);
System.out.println(formatter.formatCellValue(c));
if (c == null) {
// Nothing in the cell in this row, skip it
} else {
cells.add(c);
}
}
}else{
System.out.println("could not find column " + columnWanted + " in first row of " + myFile.toString());
}
}
I strongly doubt that your code works in eclipse (whatever it is) and anywhere else because this line:
public static void main (String args[])
is not syntactically correct neither in Java nor in Groovy.
The "good" declaration of the entry point (although it's not required for Groovy scripts) would be:
public static void main(String[] args)
Full code just in case:
import org.apache.poi.ss.usermodel.Cell
import org.apache.poi.ss.usermodel.DataFormatter
import org.apache.poi.ss.usermodel.Row
import org.apache.poi.xssf.usermodel.XSSFSheet
import org.apache.poi.xssf.usermodel.XSSFWorkbook
public static void main(String[] args) throws IOException {
GetExcelTableInto2DArrayListString("C:\\Users\\val1\\Desktop\\Book1.xlsx", true);
}
public static void GetExcelTableInto2DArrayListString(String excelFile, boolean debug) throws IOException {
ArrayList<String> OUT = new ArrayList<String>();
File myFile = new File(excelFile);
FileInputStream fis = null;
fis = new FileInputStream(myFile);
String columnWanted = "PhysicalIDs";
Integer columnNo = null;
XSSFWorkbook myWorkBook = null;
myWorkBook = new XSSFWorkbook(fis);
// Return first sheet from the XLSX workbook
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
// Get iterator to all the rows in current sheet
List<Cell> cells = new ArrayList<Cell>();
Row firstRow = mySheet.getRow(0); //rowIterator.next();
for (Cell cell : firstRow) {
if (cell.getStringCellValue().equals(columnWanted)) {
columnNo = cell.getColumnIndex();
}
}
System.out.println(columnNo);
DataFormatter formatter = new DataFormatter(Locale.US);
if (columnNo != null) {
for (Row row : mySheet) {
Cell c = row.getCell(columnNo);
System.out.println(formatter.formatCellValue(c));
if (c == null) {
// Nothing in the cell in this row, skip it
} else {
cells.add(c);
}
}
} else {
System.out.println("could not find column " + columnWanted + " in first row of " + myFile.toString());
}
}
More information:
Lesson: A Closer Look at the "Hello World!" Application
Busy Developers' Guide to HSSF and XSSF Features
Apache Groovy - Why and How You Should Use It
EDIT1: I have an ExcelUtility.java class to get cell data from it and pass it on to the tests methods in my test class.
I am reading from 1 excel file.
The excel file has 3 worksheets.
Every worksheet has 1 unique working table inside.
I have 1 Test class.
The test class has 3 test methods.
The test class contains 3 dataProviders.
All dataProviders differ in the worksheet name and working table name.
The tests in the test class are written in the following manner:
#Test(priority = 0, dataProvider = "dp1")
public void test01(String...strings){
}
#Test(priority = 1, dataProvider = "dp2")
public void test02(String...strings){
}
#Test(priority = 2, dataProvider = "dp3")
public void test03(String...strings){
}
I have the following java class to read from XLSX file using apache poi jars:
public class ExcelUtility {
private static XSSFWorkbook ExcelWBook;
private static XSSFSheet ExcelWSheet;
/*
* Set the File path, open Excel file
* #params - Excel Path and Sheet Name
*/
public static void setExcelFile(String path, String sheetName) throws Exception {
try {
// Open the Excel file
FileInputStream ExcelFile = new FileInputStream(path);
// Access the excel data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(sheetName);
} catch (Exception e) {
throw (e);
}
}
public static String[][] getTestData(String tableName) {
String[][] testData = null;
try {
// Handle numbers and strings
DataFormatter formatter = new DataFormatter();
XSSFCell[] boundaryCells = findCells(tableName);
XSSFCell startCell = boundaryCells[0];
XSSFCell endCell = boundaryCells[1];
int startRow = startCell.getRowIndex() + 1;
int endRow = endCell.getRowIndex() - 1;
int startCol = startCell.getColumnIndex() + 1;
int endCol = endCell.getColumnIndex() - 1;
testData = new String[endRow - startRow + 1][endCol - startCol + 1];
for (int i=startRow; i<endRow+1; i++) {
for (int j=startCol; j<endCol+1; j++) {
// testData[i-startRow][j-startCol] = ExcelWSheet.getRow(i).getCell(j).getStringCellValue();
Cell cell = ExcelWSheet.getRow(i).getCell(j);
testData[i - startRow][j - startCol] = formatter.formatCellValue(cell);
}
}
} catch (Exception e) {
e.printStackTrace();
}
return testData;
}
public static XSSFCell[] findCells(String tableName) {
DataFormatter formatter = new DataFormatter();
String pos = "begin";
XSSFCell[] cells = new XSSFCell[2];
for (Row row : ExcelWSheet) {
for (Cell cell : row) {
// if (tableName.equals(cell.getStringCellValue())) {
if (tableName.equals(formatter.formatCellValue(cell))) {
if (pos.equalsIgnoreCase("begin")) {
cells[0] = (XSSFCell) cell;
pos = "end";
} else {
cells[1] = (XSSFCell) cell;
}
}
}
}
return cells;
}
}
In order to read from the excel file I have organized the test methods in the following manner:
#DataProvider(name = "dp1")
public Object[][] dp1() throws IOException {
Object[][] testData = new Object[0][];
try {
ExcelUtility.setExcelFile(Constants.File_Path+Constants.File_Name, "Page1");
testData = ExcelUtility.getTestData("P1");
} catch (Exception e) {
e.printStackTrace();
}
return testData;
}
#DataProvider(name = "dp2")
public Object[][] dp2() throws IOException {
Object[][] testData = new Object[0][];
try {
ExcelUtility.setExcelFile(Constants.File_Path+Constants.File_Name, "Page2");
testData = ExcelUtility.getTestData("P2");
} catch (Exception e) {
e.printStackTrace();
}
return testData;
}
#DataProvider(name = "dp3")
public Object[][] dp3() throws IOException {
Object[][] testData = new Object[0][];
try {
ExcelUtility.setExcelFile(Constants.File_Path+Constants.File_Name, "Page3");
testData = ExcelUtility.getTestData("P3");
} catch (Exception e) {
e.printStackTrace();
}
return testData;
}
#Test(priority = 0, dataProvider = "dp1")
public void test01(String...strings){
//read data from excel and pass the value to the strings added as arguments in the method above
}
#Test(priority = 1, dataProvider = "dp2")
public void test02(String...strings){
}
#Test(priority = 2, dataProvider = "dp3")
public void test03(String...strings){
}
What I would like to do is the following:
Read first row data from sheet1, pass it to test1, continue to test2
Read first row data from sheet2, pass it to test2, continue to test3
Read first row data from sheet3, pass it to test3, continue to test1
Read second row data from sheet 1, pass it to test1, continue to test2
And so on, depending of number of rows in the excel sheets.
What happens is:
The first test is executed, reads worksheet 1, row 1.
The first test is executed, reads worksheet 1, row 2.
The second test is executed, reads worksheet 2, row 1.
The second test is executed, reads worksheet 2, row 2.
All tests fail because they are dependable from each other, that is why I set execution priority.
Should I change something in the Test class, or something in the ExcelUtility.java class should be changed?
Thank you in advance!
See files related to the commit
It creates testng.xml based on xlsx with test data.
Is there a library that allows for the display of an excel sheet/workbook inside a FX GUI? It does not need to be modifiable.
I am using apache POI for the reading and writing of documents.
Thanks in advance.
As an update on how I solved this. I used controlsFX's SpreadsheetView to display the excel sheet I read using the poi library. All that was required was to read the sheet and build up the data for the view. I added the code below.
/**
* This class allows for the displaying of excel files within a window by
* utilizing SpreadsheetView from controlsFX and the reading capabilities of the POI library.
*
* Only usable for .xlsx files
*
* #author TM
*
*/
public class ExcelView {
/**
* Path to Excel
*/
private String filePath;
private int sheetIndex;
private boolean editible;
private FileInputStream inStream;
private XSSFWorkbook poiWorkbook;
private XSSFSheet poiSheet;
private SpreadsheetView theView;
public ExcelView(String path, int sheetIndex ,boolean editable){
filePath =path;
this.editible =editable;
this.sheetIndex =sheetIndex;
}
public ExcelView(String path, int sheetIndex){
filePath =path;
this.editible =false;
this.sheetIndex = sheetIndex;
}
private void initializeView() throws Exception{
GridBase grid = excelToGrid();
theView = new SpreadsheetView(grid);
theView.setEditable(editible);
}
public SpreadsheetView getView() throws Exception{
initializeView();
return theView;
}
public void showInNewWindow(){
Parent root;
try {
initializeView();
root = theView;
Stage stage = new Stage();
stage.setTitle(new File(filePath).getName());
stage.setScene(new Scene(root, 450, 450));
stage.getIcons().addAll(ResourceLoader.getIcons("Excel.ico"));
stage.show();
}
catch (Exception e) {
e.printStackTrace();
}
}
/**
* Updates the values in the view. This may happen after the Excel file has been
* modified after the initial reading.
* #throws Exception
*/
public void updateView() throws Exception{
GridBase newgrid = excelToGrid();
theView.setGrid(newgrid);
}
/**
* Creates a {#link GridBase} object from the excel file located at the path
* #return
* #throws Exception - when opening the file
*/
private GridBase excelToGrid() throws Exception{
// Read the Excel document and collect the rows
openBook();
poiSheet = poiWorkbook.getSheetAt(sheetIndex);
int[] size = getSize();
GridBase grid = new GridBase(size[0], size[1]);
ObservableList<ObservableList<SpreadsheetCell>> rows = FXCollections.observableArrayList();
Row poiRow;
Cell cell;
String value;
FormulaEvaluator evaluator = poiWorkbook.getCreationHelper().createFormulaEvaluator();
for (int row = 0; row < grid.getRowCount(); ++row) {
final ObservableList<SpreadsheetCell> list = FXCollections.observableArrayList();
poiRow = poiSheet.getRow(row);
for (int column = 0; column < grid.getColumnCount(); ++column) {
cell = poiRow.getCell(column);
value = ExcelUtils.cellStringValue(evaluator,cell);
list.add(SpreadsheetCellType.STRING.createCell(row, column, 1, 1,value));
}
rows.add(list);
}
grid.setRows(rows);
closeBook();
return grid;
}
/**
* Calculates the number of rows and columns in the sheet by looping
* and reading all the things :)
* #return the size as int[{rows, cols}]
*/
private int[] getSize(){
int numRows = 0;
int numCols =0;
int nullRowCounter = 0;
int nullColCounter = 0;
int maxNullRows = 6;
int maxNullCols = 6;
Row row;
Cell cell;
int localColCounter;
while(true){
row= poiSheet.getRow(numRows);
numRows++;
// Check row...
if(row == null){
nullRowCounter++;
}
else{
nullRowCounter = 0;
// If row not null, check columns...
localColCounter = 0;
while(true){
cell = row.getCell(localColCounter);
localColCounter++;
if(cell==null){
nullColCounter++;
}else{
nullColCounter = 0;
}
if(nullColCounter == maxNullCols){
// reached max null cells
localColCounter -= maxNullCols;
if(localColCounter > numCols)
numCols = localColCounter;
break;
// go to next row...
}
}
}
if(nullRowCounter == maxNullRows){
// reached max null rows
numRows -= maxNullRows;
break;
}
}
return new int[]{numRows, numCols};
}
private void openBook() throws Exception{
try {
File myFile = new File(filePath);
inStream = new FileInputStream(myFile);
poiWorkbook = new XSSFWorkbook (inStream);
}catch (Exception e) {
e.printStackTrace();
throw e;
}
}
private void closeBook() throws Exception{
try {
poiWorkbook.close();
inStream.close();
}catch (Exception e) {
e.printStackTrace();
throw e;
}
}
}
I am trying to set or write the result of execute test cases using JXL in key driven framework. Also, I am able to write or set the result but only in first iteration. At the time of second iteration it shows null pointer exception. I tried but don't understand what the exact problem is?
Main Method:
public class MainClass {
private static final String BROWSER_PATH = "D:\\FF18\\firefox.exe";
private static final String TEST_SUITE_PATH = "D:\\configuration\\GmailTestSuite.xls";
private static final String OBJECT_REPOSITORY_PATH = "D:\\configuration\\objectrepository.xls";
private static final String ADDRESS_TO_TEST = "https://www.gmail.com";
// other constants
private WebDriver driver;
private Properties properties;
/* private WebElement we; */
public MainClass() {
File file = new File(BROWSER_PATH);
FirefoxBinary fb = new FirefoxBinary(file);
driver = new FirefoxDriver(fb, new FirefoxProfile());
driver.get(ADDRESS_TO_TEST);
}
public static void main(String[] args) throws Exception {
MainClass main = new MainClass();
main.handleTestSuite();
}
private void handleTestSuite() throws Exception {
ReadPropertyFile readConfigFile = new ReadPropertyFile();
properties = readConfigFile.loadPropertiess();
ExcelHandler testSuite = new ExcelHandler(TEST_SUITE_PATH, "Suite");
testSuite.columnData();
int rowCount = testSuite.rowCount();
System.out.println("Total Rows=" + rowCount);
for (int i = 1; i < rowCount; i++) {
String executable = testSuite.readCell(
testSuite.getCell("Executable"), i);
System.out.println("Executable=" + executable);
if (executable.equalsIgnoreCase("y")) {
// exe. the process
String scenarioName = testSuite.readCell(
testSuite.getCell("TestScenario"), i);
System.out.println("Scenario Name=" + scenarioName);
handleScenario(scenarioName);
}
}
WritableData writableData= new WritableData(TEST_SUITE_PATH,"Login");
writableData.shSheet("Login", 5, 1, "Pass");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
writableData.shSheet("Login", 5, 2, "Fail");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
writableData.shSheet("Login", 5, 3, "N/A");
driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
}
private void handleScenario(String scenarioName) throws Exception {
ExcelHandler testScenarios = new ExcelHandler(TEST_SUITE_PATH);
testScenarios.setSheetName("Login");
testScenarios.columnData();
int rowWorkBook1 = testScenarios.rowCount();
for (int j = 1; j < rowWorkBook1; j++) {
String framWork = testScenarios.readCell(
testScenarios.getCell("FrameworkName"), j);
String operation = testScenarios.readCell(
testScenarios.getCell("Operation"), j); // SendKey
String value = testScenarios.readCell(
testScenarios.getCell("Value"), j);
System.out.println("FRMNameKK=" + framWork + ",Operation="
+ operation + ",Value=" + value);
handleObjects(operation, value, framWork);
}
}
private void handleObjects(String operation, String value, String framWork)
throws Exception {
System.out.println("HandleObject--> " + framWork);
ExcelHandler objectRepository = new ExcelHandler(
OBJECT_REPOSITORY_PATH, "OR");
objectRepository.columnData();
int rowCount = objectRepository.rowCount();
System.out.println("Total Rows in hadleObject=" + rowCount);
for (int k = 1; k < rowCount; k++) {
String frameWorkName = objectRepository.readCell(
objectRepository.getCell("FrameworkName"), k);
String ObjectName = objectRepository.readCell(
objectRepository.getCell("ObjectName"), k);
String Locator = objectRepository.readCell(
objectRepository.getCell("Locator"), k); // SendKey
System.out.println("FrameWorkNameV=" + frameWorkName
+ ",ObjectName=" + ObjectName + ",Locator=" + Locator);
if (framWork.equalsIgnoreCase(frameWorkName)) {
operateWebDriver(operation, Locator, value, ObjectName);
}
}
}
private void operateWebDriver(String operation, String Locator,
String value, String objectName) throws Exception {
System.out.println("Operation execution in progress");
WebElement temp = getElement(Locator, objectName);
if (operation.equalsIgnoreCase("SendKey")) {
temp.sendKeys(value);
}
Thread.sleep(1000);
driver.manage().timeouts().implicitlyWait(10, TimeUnit.SECONDS);
if (operation.equalsIgnoreCase("Click")) {
temp.click();
}
if (operation.equalsIgnoreCase("Verify")) {
System.out.println("Verify--->" +temp);
temp.isDisplayed();
}
}
public WebElement getElement(String locator, String objectName)
throws Exception {
WebElement temp = null;
System.out.println("Locator-->" + locator);
if (locator.equalsIgnoreCase("id")) {
temp = driver.findElement(By.id(objectName));
} else if (locator.equalsIgnoreCase("xpath")) {
temp = driver.findElement(By.xpath(objectName));
System.out.println("xpath temp ----->" + temp);
} else if (locator.equalsIgnoreCase("name")) {
temp = driver.findElement(By.name(objectName));
}
return temp;
}
}
WritableData
public class WritableData {
Workbook wbook;
WritableWorkbook wwbCopy;
String ExecutedTestCasesSheet;
WritableSheet shSheet;
public WritableData(String testSuitePath, String OBJECT_REPOSITORY_PATH) throws RowsExceededException, WriteException {
// TODO Auto-generated constructor stub
try { wbook = Workbook.getWorkbook(new File(testSuitePath));
wwbCopy= Workbook.createWorkbook(new File(testSuitePath),wbook);
System.out.println("writable workbookC-->" +wwbCopy);
shSheet=wwbCopy.getSheet("Login");
System.out.println("writable sheetC-->" +shSheet);
//shSheet = wwbCopy.createSheet("Login", 1);
} catch (Exception e) {
// TODO: handle exception
System.out.println("Exception message" + e.getMessage()); e.printStackTrace(); } }
public void shSheet(String strSheetName, int iColumnNumber, int
iRowNumber, String strData) throws WriteException, IOException {
// TODO Auto-generated method stub
System.out.println("strDataCC---->>" +strData);
System.out.println("strSheetName<<>><<>><<>>" +strSheetName);
WritableSheet wshTemp = wwbCopy.getSheet(strSheetName);
shSheet=wwbCopy.getSheet("Login");
WritableFont cellFont = null;
WritableCellFormat cellFormat = null;
if (strData.equalsIgnoreCase("PASS")) {
cellFont = new WritableFont(WritableFont.TIMES, 12);
cellFont.setColour(Colour.GREEN);
cellFont.setBoldStyle(WritableFont.BOLD);
cellFormat = new WritableCellFormat(cellFont);
cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN); }
else if (strData.equalsIgnoreCase("FAIL")) {
cellFont = new WritableFont(WritableFont.TIMES, 12);
cellFont.setColour(Colour.RED);
cellFont.setBoldStyle(WritableFont.BOLD);
cellFormat = new WritableCellFormat(cellFont);
cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN); }
else { cellFont = new WritableFont(WritableFont.TIMES, 12);
cellFont.setColour(Colour.BLACK);
cellFormat = new WritableCellFormat(cellFont);
cellFormat.setBorder(Border.ALL, BorderLineStyle.THIN);
cellFormat.setWrap(true); }
Label labTemp = new Label(iColumnNumber, iRowNumber, strData,
cellFormat);
shSheet.addCell(labTemp);
System.out.println("writableSheet---->"+shSheet);
wwbCopy.write();
wwbCopy.close();
wbook.close();
}
}
Console:
writable sheetC-->jxl.write.biff.WritableSheetImpl#ee1ede
strDataCC---->>Pass
strSheetName<<>><<>><<>>Login
writableSheet---->jxl.write.biff.WritableSheetImpl#ee1ede
strDataCC---->>Fail
strSheetName<<>><<>><<>>Login
writableSheet---->jxl.write.biff.WritableSheetImpl#ee1ede
Exception in thread "main" java.lang.NullPointerException
at jxl.write.biff.File.write(File.java:149)
at jxl.write.biff.WritableWorkbookImpl.write(WritableWorkbookImpl.java:706)
at com.chayan.af.WritableData.shSheet(WritableData.java:86)
at com.chayan.af.MainClass.handleTestSuite(MainClass.java:77)
at com.chayan.af.MainClass.main(MainClass.java:48)
In my program I want to find the row number in the excel sheet matching the string I have passed as argument . It works fine for first and second row but problem is with the next rows. My code to find row number is as below :
public int findrownum(String sName, String value, int cNum) throws Exception{
File excel = new File(filepath);
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet(sName);
boolean check = true;
int i=0;
while (check){
XSSFRow rowH = ws.getRow(i);
XSSFCell cell = rowH.getCell(cNum);
String cellvalue = cellToString(cell);
if (cellvalue.equals(value)){
check = false;
}
else {
i = i+1;
}
}
return i;
}
}
I want to read third row that is the string with name registration from the excel
Sl No test case name result timestamp
1 login Pass 03/03/2014 12:11:43 PM
2 Registration
Please let me know what changes needs to be done in the code .
Thanks
I used the similar logic as mentioned by #eric in JUNIT now i am able to find the row number .But now its giving error while i try to read the data using this row number . My code to read data is as below . Please let me know what changes needs to be done public String dataread(String sName, int rNum, String cName) throws Exception{
File excel = new File(filepath);
FileInputStream fis = new FileInputStream(excel);
XSSFWorkbook wb = new XSSFWorkbook(fis);
XSSFSheet ws = wb.getSheet(sName);
XSSFRow rowH = ws.getRow(rNum-1);
int totalRows = ws.getLastRowNum();
int i =0;
for(i=0;i<=totalRows;i++)
{
XSSFCell cell = rowH.getCell(i);
String value = cellToString(cell);
if (value.equals(cName)){
System.out.println(i);
break;
}
}
XSSFRow row = ws.getRow(rNum);
XSSFCell cell = row.getCell(i);
String value = cellToString(cell) return value;
}
In general From this Documentation you can use the getHeight() to get in which your cursor instead of writing up your own loop. Obviously this would reduce the execution time as well. Also the code which you have written could have caused the exception,as there is no more physical rows.
ws.getRow(i); can cause a fatal error if i>height of the last row
Hope the following code helps. The assumption is the data in the cell is string data. Also this is with apache poi api.
public static String getcellValue(int testRowNo, int colNo)
{
String projectPath = System.getProperty("user.dir");
String excelPath = projectPath + "/TestSet.xlsx";
File excel = new File(excelPath);
FileInputStream fis = null;
Workbook workBook = null;
String cellValue = null;
try
{
fis = new FileInputStream(excel);
workBook = WorkbookFactory.create(fis);
Sheet workSheet = workBook.getSheet(sheetName);
int totalRows = workSheet.getLastRowNum();
Row row = null;
cellValue = workSheet.getRow(testRowNo).getCell(colNo).getStringCellValue();
} catch (InvalidFormatException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}finally
{
try
{
fis.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return cellValue;
}
public static int getrowNumber(String sheetName, String cellData)
{
String projectPath = System.getProperty("user.dir");
String excelPath = projectPath + "/TestSet.xlsx";
File excel = new File(excelPath);
FileInputStream fis = null;
Workbook workBook = null;
String cellValue = null;
try
{
fis = new FileInputStream(excel);
workBook = WorkbookFactory.create(fis);
Sheet workSheet = workBook.getSheet(sheetName);
int totalRows = workSheet.getLastRowNum();
Row row = null;
int testRowNo = 0;
for(int rowNo =1; rowNo<=totalRows; rowNo++)
{
row = workSheet.getRow(rowNo);
testRowNo = testRowNo +1;
if(row.getCell(0).getStringCellValue().equalsIgnoreCase(cellData))
{
break;
}
}
} catch (InvalidFormatException e)
{
e.printStackTrace();
} catch (IOException e)
{
e.printStackTrace();
}finally
{
try
{
fis.close();
} catch (IOException e)
{
e.printStackTrace();
}
}
return testRowNo;
}