I am working on a Data Driven Project where my test data is from an excel sheet. Am able to fetch data from sheet, but I need to pass only the column value but not Row value in step defn method, so that my test case can complete one set of testing with one row and move to next row.
My code:
public static int getCellData() throws Exception{
int rowData=0;
int NumOfRows=0;
try{
NumOfRows = ExcelWSheet.getPhysicalNumberOfRows();
for(int i=2;i<NumOfRows;i++){
rowData = ExcelWSheet.getRow(i).getPhysicalNumberOfCells();}
}
catch (Exception e){}
return rowData;
}
Related
I have below loop trying to printout keys and values stored in a hashmap
// Create the first row corresponding to the header
Row header = Sheet.createRow(0);
int headerIndex = 0;
for (Map.Entry<String, List<String>> entry : resultsToPrint.entrySet()) {
String key = entry.getKey();
header.createCell(headerIndex).setCellValue(key);
int rowIndex = 1;
for (String value : entry.getValue()) {
// Creating row
Row row = Sheet.createRow(rowIndex);
// create cell
row.createCell(headerIndex).setCellValue(value);
rowIndex++;
}
headerIndex++;
}
the results I am getting looks like this:
This is what gets printed
what I need this loop to do, is to populate the values of the second column as well and if I add a third column, it needs to populate the values for the third column etc.
Please assist
I am trying to fetch the data from the Numbers application in macOS, In below code is not able to fetch the value from the cell.
public class Excel {
public static String getdata(String sheetname, int rowvalue, int cellvalue)
{
String value = "";
try {
FileInputStream fis = new FileInputStream("./Excel/Logincred.xlsx");
Workbook wb = WorkbookFactory.create(fis);
Sheet sh = wb.getSheet(sheetname);
Row r = sh.getRow(rowvalue);
Cell c = r.getCell(cellvalue);
value = c.toString();
}
catch(Exception e)
{
}
return value;
}
}
You need to append ' before each number in your excel sheet and then your code would work completely fine.
So lets say, you have a value 4 in your excel, you need to change it to '4 and then your read from excel would work
I have the following code using the Google sheets API and got it working perfectly. It sees all my data and puts it into the app perfectly via the for loop. It runs through the spreadsheets and puts the data in an edit view.
private List<String> getDataFromApi() throws IOException {
String spreadsheetId = "1BxiMVs0XRA5nFMdKvBdBZjgmUUqptlbs74OgvE2upms";
String range = "Class Data!A2:E";
List<String> results = new ArrayList<String>();
ValueRange response = this.mService.spreadsheets().values()
.get(spreadsheetId, range)
.execute();
List<List<Object>> values = response.getValues();
if (values != null) {
results.add("Name, Major");
for (List row : values) {
results.add(row.get(0) + ", " + row.get(4));
}
}
return results;
}
As you can see, the for loop retrieves the data one by one until there is no more data inside a specific range in the spreadsheet.
My question: I want to retrieve a specific range, not using a for loop. However, as an example, if I want to get cell A1, and I do result.add(A.get(0)), it doesn't work.
How can I retrieve a specific range within the spreadsheet.
When trying to get the Input the data from the Excel Sheet while working with OATS tool, it always gets into the catch block of the function. The below is the script written. Please help us resolve this issue.
public String getInputfromExcel(int argColumnNumber,int argRowNumber)throws Exception
{
String inputExcelName = dataPath+".xlsx";
String cellContent = "12";
try
{
Workbook workbook = Workbook.getWorkbook(new File(inputExcelName));
Sheet sheet = workbook.getSheet(0);
Cell a1 = sheet.getCell(argColumnNumber, argRowNumber);
cellContent = (a1.getContents()).toString();
System.out.println(cellContent.toString());
workbook.close();
}
catch (Exception e)
{
addReport("Getting Input From Excel", "Fail","Exception while reading value from excel sheet");
}
return cellContent;
}
Axel has brought up the point. On a further note, if I remember correctly, the function sheet.getCell(arg1, arg2) has first argument as rowNumber and 2nd as columnNumber (both the values are 0 based index).
Its old quetion....but just posting answer it might be helpful for someone needy.
In Oracle Application Testing Suite. NO NEED of external JARs to read/write data.
You can enable DataTable module in the tool
Complete explanation given here, http://www.testinghive.com/how-to-read-write-excel-in-oats/
//Define Sheet name to be read, and provide comma seperated to read multiple sheets
String sheetName = "Sheet1";
//Mention excel sheet path
String strFile= "C:\\Demo\\test.xls";
//Defined array list to add Sheets to read
List sheetList = new ArrayList();
sheetList.add(sheetName);
// Iports Sheet1
datatable.importSheets(strFile, sheetList, true, true);
//get rowcount
info("Total rows :"+datatable.getRowCount());
int rowcount=datatable.getRowCount();
//Loop to read all rows
for (int i=0;i<rowcount;i++)
{
//Set current row fromw here you need to start reading, in this case start from first row
datatable.setCurrentRow(sheetName, i);
String strCompany=(String) datatable.getValue(sheetName,i,"Company");
String strEmpFName=(String) datatable.getValue(sheetName,i,"FirstName");
String strEmpLName=(String) datatable.getValue(sheetName,i,"LastName");
String strEmpID=(String) datatable.getValue(sheetName,i,"EmpID");
String strLocation=(String) datatable.getValue(sheetName,i,"Location");
//prints first name and last name
System.out.println("First Name : "+strEmpFName+", Last Name : "+strEmpLName);
//Sets ACTIVE column in excel sheet to Y
String strActive="Y";
datatable.setValue(sheetName, i, datatable.getColumn(sheetName, datatable.getColumnIndex("Active")), strActive);
}
//Updates sheet with updated values ie ACTIVE column sets to Y
datatable.exportToExcel("C:\\Demo\\test1.xlsx");
I am creating a java program to read an excel sheet and create a comma separated file. When I run my sample excel file, with blank columns, The first row works perfectly, but the rest of the rows skip the blank cells.
I have read about the code changes required to insert blank cells into the rows, but my question is why does the first row work ????
public ArrayList OpenAndReadExcel(){
FileInputStream file = null;
HSSFWorkbook workBook = null;
ArrayList <String> rows = new ArrayList();
//open the file
try {
file = new FileInputStream(new File("Fruity.xls"));
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
System.out.println("Could not open Input File");
e.printStackTrace();
}
// open the input stream as a workbook
try {
workBook = new HSSFWorkbook(file);
} catch (IOException e) {
// TODO Auto-generated catch block
System.out.println("Can't Open HSSF workbook");
e.printStackTrace();
}
// get the sheet
HSSFSheet sheet = workBook.getSheetAt(0);
// add an iterator for every row and column
Iterator<Row> rowIter = sheet.rowIterator();
while (rowIter.hasNext())
{
String rowHolder = "";
HSSFRow row = (HSSFRow) rowIter.next();
Iterator<Cell> cellIter = row.cellIterator();
Boolean first =true;
while ( cellIter.hasNext())
{
if (!first)
rowHolder = rowHolder + ",";
HSSFCell cell = (HSSFCell) cellIter.next();
rowHolder = rowHolder + cell.toString() ;
first = false;
}
rows.add(rowHolder);
}
return rows;
}
public void WriteOutput(ArrayList<String> rows) {
// TODO Auto-generated method stub
PrintStream outFile ;
try {
outFile = new PrintStream("fruity.txt");
for(String row : rows)
{
outFile.println(row);
}
outFile.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
-----
my Input in .xls file (Sorry don't know how to insert an excel table here )
Name >>>>>>>>>> Country of Origin >>>>>>>>> State of origin >>>>>>> Grade>>>>>> No of months
Apple >>>>>>>> USA >>>>>>>>>>>>>>>>>>>>>> Washington >>>>>>>>>>>>>> A >>>>>>>>> 6
orange >>>>>> USA >>>>>>>>>>>>>>>>>>>>>> Florida >>>>>>>>>>>>>>>>> A >>>>>>>>> 9
pineapple>>>>> USA >>>>>>>>>>>>>>>>>>>>>> Hawaii >>>>>>>>>>>>>>>>>> B >>>>>>>>> 10
strawberry>>>> USA >>>>>>>>>>>>>>>>>>>>>> New Jersey>>>>>>>>>>>>>> C >>>>>>>>>> 3
my output text file
Name ,Country of Origin,State of origin,,,Grade,No of months
Apple,USA,Washington,A,6.0
orange,USA,Florida,A,9.0
pineapple,USA,Hawaii,B,10.0
strawberry,USA,New Jersey,C,3.0
Notice the two extra commas before the Grade column... This is because I have two blank columns there.<br/>
These extra commas are missing in the rest of the output.
I am using Apache Poi-3.9-20121203.jar
You should have a read through the Iterating Over Rows and Cells documentation on the Apache POI website.
The CellIterator will only return cells that have been defined in the file, which largely means ones with either values or formatting. The excel file format is sparse, and doesn't bother storing cells which have neither values nor formatting.
For your case, you must have formatting applied to the first row, which causes them to show up.
You need to read through the documentation and switch to lookups by index. That will also allow you full control over how blank vs never used cells are handled in your code.
CellIterator does not iterate over cells which do not have any formatting or value applied.
First row must have had at least value or formatting applied.
If you want to read such cells as well you need to address it directly by specifying cell number
row.getCell(cellNumber, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
Using Row.MissingCellPolicy.CREATE_NULL_AS_BLANK returns it as a blank cell.