Read one row per time / only specific column and create object - java

I using Apache poi to import an .xlsx file that I have in my desktop area.
With the below code I can read the hole sheet that I want.
But I want to read only one line per time and only specific columns per line (for example I want only column A, F and G from the first line and save it as object, then the same for the second line, third line etc )
How can I do it?
public class main {
public static void main( String[] args ) throws Exception {
InputStream ExcelFileToRead = new FileInputStream("C:/User/Desktop/test.xlsx");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFSheet sheet=wb.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING)
{
System.out.print(cell.getStringCellValue()+" ");
}
else if(cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC)
{
System.out.print(cell.getNumericCellValue()+" ");
}
else
{
}
}
System.out.println();
}
}
}

A specific row can be retrieved from the Sheet object using
Sheet.getRow(index)
Where index is a zero based row number. That is, to read row 1, you must get the row at index zero, row 2 is at index 1 and so on. Similarly a specific cell can be retrieved from it's Row object using
Row.getCell(index)
Once again index is a zero based cell number where cell column A is at index 0, column B is at index 1 and so on. Therefore to retrieve the Cell at B2, you could use
Cell cell = Sheet.getRow(1).getCell(1);

Related

Cell value obtained with Apache POI from Excel Spreadsheet prints same value as Java String but IF statement does not say they are the same?

I am reading cells from an Excel spreadsheet. I am reading the first cell in each row, and comparing them to a String object that I have passed into the function. The function correctly iterates over all rows and accesses the first cell in each row, but when comparing them to the String object parameter, the IF statement does not execute, despite both the value obtained from the cell and the String parameter printing the same thing. I have used '==' operators, as well as .equals() but nothing seems to let the IF statement execute.
public static ArrayList<Integer> returnCurrency(String currency, String fileName) throws IOException
{
FileInputStream excelFile = new FileInputStream(newFile(fileName));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet sheet = workbook.getSheetAt(0);
Iterator<Row> iterator = sheet.iterator();
ArrayList<Double> currencyRateArray = new ArrayList<Double>();
for( int rowNum = 0; rowNum <= sheet.getLastRowNum(); rowNum++)
{
Row row = sheet.getRow(rowNum);
Cell tempCell = row.getCell(0);
System.out.printf("temp cell has value of:%s\n",tempCell.getStringCellValue());
System.out.printf("currency variable is: %s\n", currency);
if(currency.equals(tempCellString))
{
System.out.println("Found the currency\n");
}
}
}
When I pass the parameter String as "USD", both print statements print "USD", but it will never print "Found the currency" as that IF statement does not execute. Any help would be appreciated :)
Found the answer - the cell in the database had the value 'USD ' instead of 'USD'.

How to iterate from first row of excel and try to login and then again iterate to second row and try to login again using Selenium with POI?

My scenario is I have an excel with three rows and two columns. First Column is User Name and second column is Password and under which three rows with some data exists.
My target is my webdriver script reads the first row data and tries to login then reads the second row data and again try to login and so on.
The script I have create is it reads first username and put it in the user Name text box and reads first password and put in password and then try to login and never goes to second row data. My guess is the break I used in the script is not at correct place
I dont know where I should break the the loop to go from row to row.
Here is my code:
FileInputStream loginFile = new FileInputStream(new File("C:\\Selenium\\Input_Data\\LoginFailure.xlsx"));
//Get the workbook instance for xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(loginFile);
//Get the first sheet of the xlsx file
XSSFSheet sheet = workbook.getSheet("Login");
//Iterate through each row from first sheet
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.getColumnIndex()==0)
{
driver.findElement (By.id("UserName")).sendKeys(cell.getStringCellValue());
}
else
driver.findElement(By.id("Password")).sendKeys(cell.getStringCellValue());
}
break;
}
driver.findElement(By.id("LoginButton")).click();
System.out.println("**********User login failure**********");
Instead of putting break ..Can you please try to put continue and let me know the results.
break will go out of the loop.However, continue will go to the next iteration.
You should break out of the cellIterator after you got your username and password in order to continue with the outer loop for the rows.
while (cellIterator.hasNext())
{
Cell cell = cellIterator.next();
if(cell.getColumnIndex() == 0)
{
driver.findElement (By.id("UserName")).sendKeys(cell.getStringCellValue());
}
else
{
driver.findElement(By.id("Password")).sendKeys(cell.getStringCellValue());
}
if(cell.getColumnIndex() > 0)
{
break;
}
}
Break the inner while loop when you get both username and password.
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.getColumnIndex()==0)
{
driver.findElement (By.id("UserName")).sendKeys(cell.getStringCellValue());
}else if(cell.getColumnIndex()==1){
driver.findElement(By.id("Password")).sendKeys(cell.getStringCellValue());
}else{
break;
}
}
driver.findElement(By.id("LoginButton")).click();
}

Blank rows is skipped while reading data from the excel sheet

i try to read the data from excel and store in vector list. But i'm having two issue when applied the following code in my system, hope can get some guidance.
1) When i run the system it will read all the data from the excel file but it skipped those blank data. How can i make it as empty string rather than skipped. Result : from this Excel file you can see that between value 145 and 2DHatchback is blank data, but system will skipped it, how can i make it as empty string " "?.
[PAS, 04/01/2015, ALFA ROMEO, 145, 2D HATCHBACK, 5 SP MANUAL, 1598.42, GZ095G, 02, 01, 02, MULTI POINT F/INJ, ITALY, 9400, 7800]
2) When i tried to deleted few rows of data in excel, my vector result still will keep the deleted data but remain as empty.
Result: from this Excel file if i manually delete row 11 and row 12, when i system.out.println the vector result it will show as [, , ] , [, , ] for deleted rows.
Readexcel.java
public Vector getexcel(String filename)
{
String filetype = filename.substring(filename.lastIndexOf(".")+1);
Vector cellVectorHolder = new Vector();
try
{
Workbook workBook = WorkbookFactory.create(new FileInputStream(filename));
Sheet sheet = workBook.getSheetAt(0);
Iterator rowIter = sheet.rowIterator();
if(filetype.equals("xlsx"))
{
while(rowIter.hasNext())
{
XSSFRow row = (XSSFRow) rowIter.next();
Iterator cellIter = row.cellIterator();
Vector cellStoreVector=new Vector();
if(row.getRowNum()>1)
{
while(cellIter.hasNext())
{
XSSFCell cell = (XSSFCell) cellIter.next();
Integer cellType = cell.getCellType();
String cellTypeDesc = "";
String cellValue = "";
switch (cellType)
{
case 0:
cellTypeDesc = "NUMERIC";
String doubleValue = cell.getRawValue();
if (HSSFDateUtil.isCellDateFormatted(cell)) {
if (HSSFDateUtil.isValidExcelDate(Double.parseDouble(doubleValue))) {
Date date = HSSFDateUtil.getJavaDate(Double.parseDouble(doubleValue));
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
cellValue = df.format(date);
}
} else {
cellValue = String.valueOf(doubleValue);
}
break;
case 1:
cellTypeDesc = "STRING";
cellValue = cell.getStringCellValue();
break;
case 3:
cellTypeDesc = "BLANK";
cellValue = "";
break;
}
cellStoreVector.addElement(cellValue);
}
}
cellVectorHolder.addElement(cellStoreVector);
}
}
}
catch (Exception e)
{
System.out.println(e.getMessage());
}
return cellVectorHolder;
}
Excel stores empty fields, so you need to do manual checking
You should check for rows containing only empty cells. Just write a check before you add it to the cellStoreVector
Also, if the rowNumber increases by more than 1, you could add empty row-vectors yourself. So store the previous rowNumber and compare to the current rowNumber

Shift column in excel while creating excel in java using org.apache.poi.xssf.usermodel.XSSFWorkbook

how to shift the column in excel while creating excel in java using org.apache.poi.xssf.usermodel.XSSFWorkbook
XSSFWorkbook workBook = new XSSFWorkbook();
Sheet sheet = workBook.createSheet("abc");
Row sheetRow = sheet.createRow((short)0);
List headers=values fetched from db
Cell headerCell = null;
for(int k=0;k<headers.size();k++){
headerCell = sheetRow.createCell(k);
if(somecondition){
headerCell.setCellValue(rt);
}else{
sheetRow.removecell(headerCell);
}
}
.removecell is removing content but i want to delete the column,i.e shift the column to left.
try using this code
sheet.shiftRows(3, sheet.getLastRowNum(), 1);
In this code snippet, 3 is indicate row shift to 3rd index means 4th row , sheet.getLastRowNum() is indicate last row index and 1 indicate how many row is shifted.

How to hide the following Un-used rows in Excel sheet using Java Apache POI?

I am populating a template Excel sheet, with the data from the database :
for (Map<String, Object> resultRow : dbResults) {
if ((currentRow = sheet.getRow(currentDataRow)) == null) {
currentRow = sheet.createRow(currentDataRow); // Creates a new row.
}
//currentRow.getRowStyle().setHidden(false);
for (int i = 0; i < resultColumns; i++) {
currentCell = currentRow.getCell(i, Row.CREATE_NULL_AS_BLANK);
setCellValue(currentCell, resultRow.get(dbcolumnNames[i]));
}
currentDataRow += 1;
}
// How to hide all empty/Un-used rows following currentDataRow ?
Aim to Achieve :
I want that the Un-Used rows following the populated rows should be hidden ?
All Populated rows must be visible.
Eg: If 1st 100 data rows are filled, then rows following 101 and onward should be hidden.
Please, help !!
Row r = sheet.getRow(indexRow);
if ( r!=null ) {
r.setZeroHeight(true);
}
POI recognizes the number of logical rows in your sheet when you create it.
So as you populate it with 100 rows, it will create 100 records. The rest will appear when you open the XLS in Excel with the default layout - but these are not POI records.
You'll have to create some dummy rows after your last data record like this
for (int i=currentDataRow ;i<65000;i++)
sheet.createRow(i);
Create a cell style, and set it to hidden
CellStyle hiddenstyle = workBook.createCellStyle();
hiddenstyle.setHidden(true);
Set this style for all rows from your last row to end of sheet
while (rows.hasNext()){
Row row1 = rows.next ();
row1.setRowStyle(hiddenstyle);
}
row.setRowStye() and row.getRowStye() are present in poi-3.8-beta4.

Categories

Resources