I want to read a set of usernames and password from an excel sheet. My user name is present in the First column but my password values are present in the 8th column. I don't want to read the 8th column values by giving the 8th column address. Instead i want to read the password values wherever I place it in the excel sheet. Is there any way to do this ?
FileInputStream fs = new FileInputStream(strReadFile);
Workbook wb = Workbook.getWorkbook(fs);
Sheet sh = wb.getSheet("Sheet1");
int rowCount=sh.getRows();
System.out.println("No of Rows:"+rowCount);
for(int row=1;row<rowCount;row++) {
String Username = sh.getCell(1,row).getContents();
driver.findElement(By.id("user_name")).sendKeys(Username);
String Password = sh.getCell(2,row).getContents();
driver.findElement(By.id("user_pass")).sendKeys(Password);
driver.findElement(By.id("login_button")).click();
}
There is no inbuilt method As per my understanding. Check below method column for your solution.
for(int row=1;row<rowCount;row++) {
String Username = sh.getCell(column("username column",sh),row).getContents();
driver.findElement(By.id("user_name")).sendKeys(Username);
String Password = sh.getCell(column("password column",sh),row).getContents();
driver.findElement(By.id("user_pass")).sendKeys(Password);
driver.findElement(By.id("login_button")).click();
}
public int column(String columnName, Sheet sheetAt) throws Exception{
Row row = sheetAt.getRow(0);
int col = -1;
for (int i=0; i<row.getLastCellNum(); i++) {
Cell cell = row.getCell(i);
if (cell == null || cell.getCellType() == Cell.CELL_TYPE_BLANK) {
continue;
}
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
String text = cell.getStringCellValue();
if (columnName.equals(text)) {
col = i;
break;
}
}
}
if (col == -1) {
throw new Exception("None of the cells in the first row were Patch");
}
return col;
}
Related
I want to write data into excel(.xlsx file) using Apache poi. but getting some error while writing a data. I have followed this video " How to read/write data from Excel file using Apache POI API in Selenium || Latest POI Version", I m able to read data but while writing I m getting this error " Cannot invoke "org.apache.poi.xssf.usermodel.XSSFCell.getStringCellValue()" because the return value of "org.apache.poi.xssf.usermodel.XSSFRow.getCell(int)" is null ", basically nullpointerexception.
enter code here
String resourceGroupNameElement = driver.findElement(By.xpath(FrameworkValidator_Constants.Constants.RESOURCE_GROUP_NAME_XPATH)).getText();
String expectedResult = reader.getCellData("RG",6,2);
if( resourceGroupNameElement== expectedResult) {
String status= "pass";
System.out.println(status);
}
else {
String status="fail";
System.out.println(status);
}
//reader.setCellData("RG", "STATUS/PASS/FAIL", 2, status);
System.out.println(status);
reader.setCellData("RG","ACTUAL RESULT" , 2, resourceGroupNameElement);
Assert.assertEquals(resourceGroupNameElement, expectedResult);
#######
It is showing error in this section
public String setCellData(String sheetName, String colName, int rowNum, String data) {
try {
fis = new FileInputStream(path);
workbook = new XSSFWorkbook(fis);
if (rowNum <= 0)
return "";
int index = workbook.getSheetIndex(sheetName);
int colNum = -1;
if (index == -1)
return "";
sheet = workbook.getSheetAt(index);
row = sheet.getRow(0);
for (int i = 0; i < row.getLastCellNum(); i++) {
// System.out.println(row.getCell(i).getStringCellValue().trim());
if (row.getCell(i).getStringCellValue().trim().equals(colName))
colNum = i;
}
if (colNum == -1)
return "";
sheet.autoSizeColumn(colNum);
row = sheet.getRow(rowNum - 1);
if (row == null)
row = sheet.createRow(rowNum - 1);
cell = row.getCell(colNum);
if (cell == null)
cell = row.createCell(colNum);
// cell style
// CellStyle cs = workbook.createCellStyle();
// cs.setWrapText(true);
// cell.setCellStyle(cs);
cell.setCellValue(data);
fileOut = new FileOutputStream(path);
workbook.write(fileOut);
fileOut.close();
} catch (Exception e) {
e.printStackTrace();
return "";
}
return "";
}
so can anybody tell me where I m going wrong.
Have a look at the HOWTO and examples.
You will notice that there are calls for creating a row or creating a cell. Unless you do so, the row/cell does not exist and your getCell() function will return null.
Changing for loop condition part i.e. i < row.getLastCellNum(); to i < row.getLastCellNum()-1; can resolve this issue.
getLastCellNum() returns index plus one and once the counter will reach to end value, getCell(i) can point to the null value as per your code.
This method will take a String value for the name to search and return the address for the first record found in the column next to it, assuming that the name is in the first column and the address is in the second column. It will iterate over all sheets as asked. How can i change/enhance this code to Insert/Set value/Text in the third column?
public static String findAddressByName(String nameToSearch) {
String fileLocation = "I:\\foo.xlsx";
XSSFWorkbook wb = new XSSFWorkbook(new File(fileLocation));
for (int sheetIndex = 0; sheetIndex < wb.getNumberOfSheets(); sheetIndex++) {
XSSFSheet sheet = wb.getSheetAt(sheetIndex);
for (int rowIndex = 0; rowIndex < sheet.getLastRowNum(); rowIndex++) {
XSSFRow row = sheet.getRow(rowIndex);
if (row != null && row.getCell(0).getStringCellValue().equals(nameToSearch)) {
return row.getCell(1).getRawValue();
}
}
}
return "";
}
I am working in a xlsx file , where i have to just append the values in the lower row to the upper row.Also i have to skip that row from the output file.First i am giving the excel file screen
I have to append the values below the row Name6 i.e in the header there will be Name1,Name2,Name3....... Name6admin|Name6loc, Name7.
For now the since the cells are merged cell poi is giving the output as Part of a merged cell after Name6.i.e Name6|part of a merged cell that way .I want to modify that as i mentioned.
Now my code is working like I will have All the rows starting from Name1 to Name7 and all the below values they hold.And the thing is i am generating the output in a text file which can not contain the row below Name1,Name2,...etc.But i also have to append values from that . I am givinf my code
#Override
public List<String> processSheet(Sheet sheet) {
ActivityLauncher.logConsoleMsg("Processing sheet " + sheet.getSheetName() + " started");
List<String> rows = new ArrayList<String>();
Iterator<Row> rowIterator = sheet.iterator();
final int startCell=0;
while (rowIterator.hasNext()) {
Row currentRow = rowIterator.next();
StringBuilder row = new StringBuilder();
for (int i = 0; i < currentRow.getLastCellNum(); i++) {
//skipping the rows which i can not contains in the output
if(currentRow.getRowNum()==0 || currentRow.getRowNum()==1|| currentRow.getRowNum()==2|| currentRow.getRowNum()==3|| currentRow.getRowNum()==4|| currentRow.getRowNum()==5|| currentRow.getRowNum()==6|| currentRow.getRowNum()==7|| currentRow.getRowNum()==9|| currentRow.getRowNum()==10|| currentRow.getRowNum()==11) {
continue;
}
//removing the last three rows containing total
if (currentRow.getLastCellNum() < 0 || currentRow.getCell(startCell) == null || "".equals(currentRow.getCell(startCell).getStringCellValue()) || (currentRow.getCell(startCell).getStringCellValue() != null && currentRow.getCell(startCell).getStringCellValue().contains("Total"))) {
continue;
}
else {
Cell currentCell = currentRow.getCell(i, Row.MissingCellPolicy.CREATE_NULL_AS_BLANK);
String cellValue = excelManager.evalCell(currentCell);
if (!cellValue.isEmpty()) {
row.append(cellValue);
}
//adjusting the cell values with the | or BLANK
if(currentCell == null || currentCell.getCellType() == Cell.CELL_TYPE_BLANK) {
row.append("");
}else {
row.append(SEPARATOR);
}
}
}
if (!row.toString().isEmpty()) {
rows.add(row.toString());
}
}
ActivityLauncher.logConsoleMsg("Processing sheet " + sheet.getSheetName() + " completed");
return rows;
}
Abstract of the module which gets book name, sheet name and column name as arguments and expecting the module to return the desired row index.
public int getExcelData(String WBookName, String sheetName, String columnName) {
int colNum = -1;
int rowIndex = -1;
InputStream inputStream = getClass().getClassLoader().getResourceAsStream("/"+WBookName+".xls");
try {
excelWBook = new XSSFWorkbook(inputStream);
Log.info(WBookName+"Excel File loaded Successfully");
} catch (IOException e) {
Log.fatal("Unable to load"+WBookName+" Excel File");
e.printStackTrace();
}
excelWSheet = excelWBook.getSheet(sheetName);
row = excelWSheet.getRow(0);
for(int i=0; i<row.getLastCellNum();i++) {
if(row.getCell(i).getStringCellValue().trim().equals(columnName)){
colNum = i;
}
}
{
//code for getting last non-empty row for a columnName (Possible using Iterator?)
}
return rowIndex;
As Apache POI has the method Sheet#getLastRowNum(), I would use a for-loop going backwards from excelWSheet.getLastRowNum() to 0 and ask each row for a presence of a value.
The code would be something like (you should try it yourself, I am now just "programming in the browser") this:
for (int rowNum = excelWSheet.getLastRowNum(); rowNum >= 0; rowNum--) {
final Row row = excelWSheet.getRow(rowNum);
if (row != null && row.getCell(colNum) != null) {
rowIndex = rowNum;
break;
}
}
I'm trying to find a blank value in excel (xlsx) sheet and replace with some string like "ENTER VALUE" using my program with Apache POI library as below
I'm able to read and identify blank/null values in excel sheet but couldnt insert any value into those cells
public static void main(String args[]) throws IOException, InvalidFormatException
{
FileInputStream inputFile = new FileInputStream("//Users//suk//Documents/tes//testexcel.xlsx");
//now initializing the Workbook with this inputFie
// Create workbook using WorkbookFactory util method
Workbook wb = WorkbookFactory.create(inputFile);
// creating helper for writing cells
CreationHelper createHelper = wb.getCreationHelper();
// setting the workbook to handle null
wb.setMissingCellPolicy(Row.CREATE_NULL_AS_BLANK);
Sheet sheet = wb.getSheetAt(0);
for (Row row : sheet) {
int lastCellNo =row.getLastCellNum();
int firstCellNo=row.getFirstCellNum();
int rowNo =row.getRowNum();
System.out.println(" row number = "+rowNo);
System.out.println(" last cell no = "+lastCellNo);
for(int i=firstCellNo;i<lastCellNo;i++){
System.out.println("************");
Cell cell = row.getCell(i);
int colIndex =cell.getColumnIndex();
if(cell==null)
{
System.out.println(" The Cell:"+colIndex+" for row "+row.getRowNum()+" is NULL");
}
System.out.println(" column index = "+colIndex);
int cellType = cell.getCellType();
System.out.println(" cell type ="+cellType);
// writing a switch case statement
switch(cellType)
{
case 0:
{
double numValue = cell.getNumericCellValue();
//System.out.println(numValue);
break;
}
case 1:
{
String cellString = cell.getStringCellValue();
System.out.println("----String value = "+cellString+"---String length ="+cellString.length());
// here checking null consition
/* if(cellString == null || cellString.equalsIgnoreCase("") || cellString.length()<=0 || cellString.equalsIgnoreCase(" "))
{
// here creating the cell value after last cell
} */
break;
}
case 4:
{
boolean bolValue =cell.getBooleanCellValue();
//System.out.println(bolValue);
break;
}
// for case of blank cell
case 3:
{
//int lastCellPlus =lastCellNo+1;
//System.out.println("last+1 column ="+lastCellPlus);
//row.createCell(lastCellPlus).setCellValue(" NULL VALUE..PLEASE ENTER VALUE ");
System.out.println(" cell details = "+cell.getColumnIndex()+" row details ="+row.getRowNum());
cell.setCellValue(createHelper.createRichTextString("ENTER VALUE"));
System.out.println(" Sucessfully written error");
break;
}
default:
System.out.println(" unknown format");
break;
}// switch
} // row and cell iterator
}
}
}
Below is the bit of code by which im identifying its Blank/Null value and trying to insert String but its not writing to that cell
case 3:
{
//int lastCellPlus =lastCellNo+1;
//System.out.println("last+1 column ="+lastCellPlus);
//row.createCell(lastCellPlus).setCellValue(" NULL VALUE..PLEASE ENTER VALUE ");
System.out.println(" cell details = "+cell.getColumnIndex()+" row details ="+row.getRowNum());
cell.setCellValue(createHelper.createRichTextString("ENTER VALUE"));
System.out.println(" Sucessfully written error");
break;
}
if(row.getCell(0))==null || getCellValue(row.getCell(0)).trim().isEmpty()){
cell.setCellValue("ENTER VALUE");
}
private String getCellValue(Cell cell) {
if (cell == null) {
return null;
}
if (cell.getCellType() == Cell.CELL_TYPE_STRING) {
return cell.getStringCellValue();
} else if (cell.getCellType() == Cell.CELL_TYPE_NUMERIC) {
return cell.getNumericCellValue() + "";
} else if (cell.getCellType() == Cell.CELL_TYPE_BOOLEAN) {
return cell.getBooleanCellValue() + "";
}else if(cell.getCellType() == Cell.CELL_TYPE_BLANK){
return cell.getStringCellValue();
}else if(cell.getCellType() == Cell.CELL_TYPE_ERROR){
return cell.getErrorCellValue() + "";
}
else {
return null;
}
}
This should work fine:
Sheet s = wb.getSheetAt(0);
for (int rn=0; rn<s.getLastRowNum(); rn++) {
Row r = s.getRow(rn);
if (r == null) {
// No values exist in this row
r = s.createRow(rn);
}
int minColumnsPerRow=10; // Fix for your needs
for (int cn=0; cn<minColumnsPerRow; cn++) {
Cell c = r.getCell(cn);
if (c == null || c.getCellType() == Cell.CELL_TYPE_BLANK) {
// This cell is empty
if (c == null) {
c = r.createCell(cn, Cell.CELL_TYPE_STRING);
}
cell.setCellValue(createHelper.createRichTextString("ENTER VALUE"));
}
}
}
Remember that cells can be blank or null (never used), and rows can be null (never used)