I want to read excel spreadsheet(.xlxs) having testcases preconditions column/expected result column and so on. How do i read multiple columns for specific row. Everyrow(first Column)is a testcase name.
I am able to read one row and two columns, but unsure how to read multiple columns for same row . I also don't want to hardcode column#,row# while reading it. Any suggestions?
Map<String,String> arrayExcelData = new Hashtable<String,String>();
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext())
{
Row row = rowIterator.next();
Cell methodNameCol = row.getCell(0);
Cell expectedResults = row.getCell(1);
if (expectedResults != null && methodNameCol !=null)
{
arrayExcelData.put(methodNameCol.getStringCellValue(),expectedResults.getStringCellValue());
}
workbook.close();
}
The Row class provides methods that return the index of the first and last cell (aka column) in that Row instance. Use these indexes to iterate over the columns:
Row row = rowIterator.next();
short firstCellNumber = row.getFirstCellNum();
short lastCellNumber = row.getLastCellNum();
for(short cellNumber = firstCellNumber; cellNumber < lastCellNumber; cellNumber++) {
Cell dataCell = row.getCell(cellNumber);
//Do something with the dataCell here
}
Related
I use the following approach to read data from excel (csv) sheet:
InputStream inputStream = new BufferedInputStream(multipartFile.getInputStream());
XSSFWorkbook myWorkBook = new XSSFWorkbook(inputStream);
List<String> cellList = new ArrayList<>();
XSSFSheet mySheet = myWorkBook.getSheetAt(0);
Iterator<Row> rowIterator = mySheet.iterator();
rowIterator.next();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
cellList.clear();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) { // this returns false even the cell has data
Cell cell = cellIterator.next();
cellList.add(cell.getStringCellValue());
}
}
I want to make cellIterator.hasNext() returns true for empty cell values as in the second row (name). So, how can I do that?
Create Date Uuid Name
2021-09-29 2e81a2b6-3226-4fe0-b8bd-39f42239686d admin
2021-09-30 610e9040-840c-48c5-aa64-f193ed896133
You can't make cellIterator.hasNext() return true for the empty "name" cell.
If you know in advance the number of column in advance, you can use a loop and row.getCell(index).
for (int i = 0; i < 3; i++) {
Cell cell = row.getCell(i);
cellList.add(cell == null ? "Empty":cell.toString());
}
If you don't, you have to scan first of your file to count the number of columns.
I have excel file having the below data, and i am trying to fetch the data through data provider method.
The scenario here is - if the value of "To Be Executed" is "Yes" then that respective testcase scenario needs to be run.
But i am facing problem here. Find the snippet of excel file and code.
Any help would be greatly appreciated.
public Boolean getDataFromExcel(String excelName, String sheetName) {
wb = getExcelWorkbook(excelName);
Sheet sheet = wb.getSheetAt(0);
//Row firstRow = sheet.getRow(0);
Iterator<Row> rowIterator = sheet.iterator();
while(rowIterator.hasNext()) {
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext()) {
Cell cell = cellIterator.next();
if(cell.getStringCellValue().equalsIgnoreCase("Yes")){
return true;
}
else
return false;
I have excel file (*.xls or *.xlxs) which can have records or no records. First I store the file in some temp location, then copy the contents of the file and then tried to read the file. This scenario works fine if the excel sheet contains records but if the sheet has no record and the file is empty. This scenario does not work. I am using apache-poi to read the excel file contents.
public static boolean isRowEmpty(Row row) {
for (int c = row.getFirstCellNum(); c < row.getLastCellNum(); c++) {
Cell cell = row.getCell(c);
if (cell != null && cell.getCellType() != Cell.CELL_TYPE_BLANK) {
return false;
}
}
return true;
}
I get IOException : unable to read entire header 0 bytes read expected 512 bytes. Can somebody suggest me a way to get rid of this exception and check the excel file is empty?
Googling and some experiments with org.apache.poi library suggest to me that it is abnormal to check if xls file is empty without knowing even approximately the data structure within it. It's as hard as to say if, for example, Oracle BD is empty.
Any way, you are able to fetch quantity of sheets then iterate over all of them, check rows and cells and consider file is empty if you found nothing.
HSSFWorkbook wBook = new HSSFWorkbook(new FileInputStream("your_path"));
for(int i = 0; i < wBook.getNumberOfSheets(); i++){
System.out.println("Sheet " + i + " has data: " + isSheetEmpty(wBook.getSheetAt(i)));
}
boolean isSheetEmpty(HSSFSheet sheet){
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
HSSFRow row = (HSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext()) {
HSSFCell cell = (HSSFCell) cells.next();
if(!cell.getStringCellValue().isEmpty()){
return true;
}
}
}
return false;
}
Using Apache Poi (org.apache.poi) for the solution and skipping the parts where I actually get the Workbook (excel) and get access to it's sheets.
If you want to know if sheet is empty use this, modify the solution to loop through sheets to find out if all of the sheets in the file are empty.
if (sheet.getLastRowNum() == 0 && sheet.getRow(0) == null) {
// This is the case when the sheet is empty!
}
getLastRowNum() - returns 0 in case of empty sheet or if there is only data in the first row
getRow(0) - returns null if there is no data in the row
NOTE: the solution doesn't take empty strings, spaces, empty lines and etc. into account
Below code worked for me.
import java.util.Iterator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
XSSFSheet sheet = wb.getSheetAt(0);
private boolean isSheetEmpty(XSSFSheet sheet) {
Iterator rows = sheet.rowIterator();
Row row = null;
Cell cell = null;
while (rows.hasNext()) {
row = (Row) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext()) {
cell = (Cell) cells.next();
if (!cell.getStringCellValue().isEmpty()) {
return true;
}
}
}
return false;
}
if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
return true;
}
return false;
Try this one !
I am trying to read excel file data and saving that data into the database.
data is comming to console. I have two column in excel file namely Userid and RequestId I am trying to save the data similarly in the database table in the same manner.
Data is going in the table but both columns are having same value.
I need them seperately.I am using this code for reading.
FileInputStream file2 = new FileInputStream(new File("C://excel.xls"));
HSSFWorkbook workbook = new HSSFWorkbook(file2);
HSSFSheet sheet = workbook.getSheetAt(0);
Iterator<Row> rowIterator = sheet.iterator();
rowIterator.next();
while(rowIterator.hasNext())
{
Row row = rowIterator.next();
//For each row, iterate through each columns
Iterator<Cell> cellIterator = row.cellIterator();
while(cellIterator.hasNext())
{
Cell cell = cellIterator.next();
double value2=(int) cell.getNumericCellValue();
System.out.println("value1: "+value2);
}`
In console it is showing correctly but the data is not going in that manner in database
Please help me
Thanks in advance
With some Data class:
class Data {
private final double val1;
private final double val2;
public Data(final double val1; final double val2) {
this.val1 = val1;
this.val2 = val2;
}
// getters etc
}
and
final List<Data> datas = new ArrayList<>();
for (final Row r : sheet) {
// Maybe skip an header row
final Cell cell1 = r.getCell(0); // 0-based
final Cell cell2 = r.getCell(1);
if (cell1 != null && cell2 != null) {
datas.add(new Data(cell1.getNumericCellValue(), cell2.getNumericCellValue()));
}
}
// TODO: write datas to DB
NB: wild code (i.e. didn't even try to compile it)
Some reading: https://poi.apache.org/spreadsheet/quick-guide.html#Iterator
I am trying to get the column values for a specific row in a excel using poi methods.
I am able to get the values but the problem is I want the values only from second column.
public static ArrayList<String> GetBusinessComponentList() throws IOException{
String Tcname = "TC02_AggregateAutoByPassRO_CT";
ArrayList<String> arrayListBusinessFlow ;
arrayListBusinessFlow = new ArrayList<String>();
FileInputStream fileInput = new FileInputStream(oFile);
wb = new HSSFWorkbook(fileInput);
sheet = wb.getSheet("Business Flow");
int rownr = findRow(sheet, Tcname);
row = sheet.getRow(rownr);
for (Cell cell : row) {
String arr = cell.getStringCellValue();
arrayListBusinessFlow.add(arr);
}
return arrayListBusinessFlow;
}
private static int findRow(HSSFSheet sheet, String cellContent){
for (Row row : sheet) {
for (Cell cell : row) {
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
if (cell.getRichStringCellValue().getString().trim().equals(cellContent)) {
return row.getRowNum();
}
}
}
}
return 0;
}
}
OUTPUT:
[TC02_AggregateAutoByPassRO_CT,
StrategicUINewBusiness.Login,
StrategicUINewBusiness.CustomerSearch,
StrategicUINewBusiness.NamedInsured,
StrategicUINewBusiness.InsuranceScoreByPass,
StrategicUINewBusiness.VehiclePage,
StrategicUINewBusiness.DriverPage,
StrategicUINewBusiness.ViolationPage,
StrategicUINewBusiness.UnderwritingPage,
StrategicUINewBusiness.CoveragePage,
StrategicUINewBusiness.Portfolio,
StrategicUINewBusiness.BillingPage,
StrategicUINewBusiness.FinalSalePage,
StrategicUINewBusiness.PolicyConfirmation, , , ]
But I do not want my test case name when I am getting.
Please help me what changes i needed to do. thanks!
Currently, the code you're using to iterate over cells only returns cells with content or styling, and skips totally empty ones. You need to change to one of the other ways of iterating over cells, so you can control it to read from the second column onwards.
If you look at the Apache POI Documentation on iterating over rows and cells, you'll see a lot more details on the two main ways to iterate.
For your case, you'll want something like:
// We want to read from the 2nd column onwards, zero based
int firstColumn = 1;
// Always fetch at least 4 columns
int MY_MINIMUM_COLUMN_COUNT = 5;
// Work out the last column to go to
int lastColumn = Math.max(r.getLastCellNum(), MY_MINIMUM_COLUMN_COUNT);
// To format cells into strings
DataFormatter df = new DataFormatter();
// Iterate over the cells
for (int cn = firstColumn; cn < lastColumn; cn++) {
Cell c = r.getCell(cn, Row.RETURN_BLANK_AS_NULL);
if (c == null) {
// The spreadsheet is empty in this cell
} else {
// Do something useful with the cell's contents
// eg get the cells value as a string
String cellAsString = df.formatCellValue(c);
}
}
Use Cell cell=row.getCell(1); and also you can use sheet.getLastRowNum() to get the number last row on the sheet.
for (int i=0;i<=row.getLastCellNum();i++) {
if (i!=1){
//your stuff
}
}