how to read and validate blank lines from selenium excel - java

here in my code I am trying to read only the data from column "A" . Here in the screen shot I have attached how the sample data looks like. I am having an issue while reading the contents as its throwing null pointer exception because of the blank line. I need to verify the blank line as well . Please give me your thoughts
public void verifyAllSupportingLogs() throws Exception {
Sheet sheet = getFilenameSupportingLogs("c:\\DataFile");
int rowCount = sheet.getPhysicalNumberOfRows();
XSSFCell firstColumnCell = null;
int firstColumnRowCount = 0;
ArrayList<String> InnerArray = new ArrayList<>();
String cellValues = null;
String GetsupportingLogs1 = null;
for (int i = 0; i < rowCount; i++) {
try {
XSSFRow row = (XSSFRow) sheet.getRow(i);
firstColumnCell = row.getCell(0);
} catch (NullPointerException nullPointerException) {
System.out.println("Cell is null at index: " + i);
}
if (firstColumnCell != null) {
if (firstColumnCell.getStringCellValue().length() > 0) {
firstColumnRowCount = i;
}
}
}
for (int j = 0; j <= firstColumnRowCount; j++) {
XSSFRow row = (XSSFRow) sheet.getRow(j);
XSSFCell cell = row.getCell(0);
String valuesFromExcel = cell.getStringCellValue();
InnerArray.add(valuesFromExcel);
cellValues = InnerArray.toString();
}
String GetsupportingLogs = con.clickOnSupportingLogsTextbox(GetsupportingLogs1);
System.out.println("GetsupportingLogs" + GetsupportingLogs);
con.checkValueSupportingLogs(cellValues, GetsupportingLogs);
}
public void checkValueSupportingLogs(String GetsupportingLogs, String cellValue) throws Exception {
java.lang.String[] cellValue1 = cellValue.split("\n");
for (String cellValue2 : cellValue1) {
if (GetsupportingLogs.contains(cellValue2)) {
System.out.println("Success, this string is in the supporting logs.");
} else {
reportFailure("ERROR! This string is not in the supporting logs.");
}
}
}

Simply apply same check if cell is null.
Instead of:
for (int j = 0; j <= firstColumnRowCount; j++) {
XSSFRow row = (XSSFRow) sheet.getRow(j);
XSSFCell cell = row.getCell(0);
String valuesFromExcel = cell.getStringCellValue();
InnerArray.add(valuesFromExcel);
cellValues = InnerArray.toString();
}
use this:
XSSFCell cell = null;
for (int j = 0; j <= firstColumnRowCount; j++) {
XSSFRow row = (XSSFRow) sheet.getRow(j);
try {
cell = row.getCell(0);
}
catch (NullPointerException nullPointerException) {
System.out.println("Cell is null at index: " + j);
}
if (cell != null) {
String valuesFromExcel = cell.getStringCellValue();
InnerArray.add(valuesFromExcel);
cellValues = InnerArray.toString();
cell = null;
}
}
In case if different data types in the excel file, you can combine with this: Error : Cannot get a STRING value from a NUMERIC cell in Selenium

Related

How to Set/Insert text/value in Excel using Apache Poi

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 "";
}

Excel formula on the current value/cell POI

I'm working on POI application in order to manipulate excel file.
In fact the user is giving a formula and files and I am applying the formula on a output file.The formula have to modify the value of the column on the cell.
For example on the columns B, I want to apply on all my column a formula.
The user is giving to me LEFT(x,2), and I have to apply this to all the columns.
(x is defining all the columns)
But when I am applying the formula I got the formula as a String. I try to pass the cell value at the formula but of course it is not working...
I think I should copy all my data into a another excel file, work on it and copy paste them in the output file or their is another way ?
Regards,
Code:
for (int i = 0; i < cell[0].length; i++){ //Checking the header
for (int j = 0; j < ruleArray.length; j++){ //Checking the Header of the array with the rule to apply
if (cell[0][i].toString().equals(ruleArray[j][0])){ //Comparing
String testF = ruleArray[j][1];
if (testF.contains("X") || testF.contains("x")){ //Replacing X with value for the formula
for (int k = 0; k < cell.length; k++){
indexT = cell[0][i].getColumnIndex();
indexC = cell[k][i].getRowIndex()+1;
String colLetter = CellReference.convertNumToColString(indexT);
formula = testF.replace("x", colLetter+indexC);
cell[k][i].setCellType(CellType.FORMULA);
cell[k][i].setCellFormula(formula);
}
}
}
}
}
I am not rewrite your code but you can take a help from this. Create a excel file with column City and Formula and then run this code. I have attached some snapshot of excel file. I thin kit will help you. LEFT(X,2) only parse first two char from a string
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.CellReference;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
public class TestProblem
{
public static void main(String[] args) throws IOException {
InputStream inp = null;
inp = new FileInputStream("E:\\Projects\\PoiAdvanceExample\\stackProblem.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
int rowsCount = sheet.getLastRowNum();
int columnCount = sheet.getRow(0).getLastCellNum();
String[][] inputData = new String[rowsCount+1][columnCount];
for (int i = 0; i <= rowsCount; i++) {
Row row = sheet.getRow(i);
int colCounts = row.getLastCellNum();
for (int j = 0; j < colCounts; j++) {
Cell cell = row.getCell(j);
if(cell.getCellType() == CellType.NUMERIC) {
inputData[i][j] = Double.toString(cell.getNumericCellValue());
}
if(cell.getCellType() == CellType.FORMULA) {
inputData[i][j] = cell.getCellFormula();
}
if(cell.getCellType() == CellType.STRING) {
inputData[i][j] = cell.getStringCellValue();
}
}
}
writeData(inputData);
}
private static void writeData(String[][] inputData) throws IOException {
Workbook workbook = new XSSFWorkbook();
Sheet sheet = workbook.createSheet();
int r = 0;
for (String[] dataRow : inputData) {
Row row = sheet.createRow(r++);
int column = 0;
for (String dataCell : dataRow) {
Cell cell = row.createCell(column++);
if (r == 1 || column == 1) cell.setCellValue(dataCell);
else if (column == 2) {
CellReference cellReference = new CellReference(cell);
String thisR = cellReference.getCellRefParts()[1];
cell.setCellFormula("LEFT(A" + thisR + ",2)");
}
}
}
FileOutputStream fileOut = new FileOutputStream("stackProblem.xlsx");
workbook.write(fileOut);
workbook.close();
}
}
Excel file before run will be like this.
Excel file after run this code will be like this.

How to get the row index of last non-empty cell for a specific column name(passed as an argument) from an excel sheet using java?

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;
}
}

poi java code to merge cells based on common data

I have data in the above format in an excel file , I want to edit it as follows:
I have used the following code :
public void editExcelTemplate() throws FileNotFoundException, IOException
{
InputStream ExcelFileToRead = new FileInputStream("file.xls");
XSSFWorkbook wb = new XSSFWorkbook(ExcelFileToRead);
XSSFSheet sheet = wb.getSheetAt(0);
int rows = sheet.getPhysicalNumberOfRows();
String cmp = "none";
for(int i=0;i<rows;i++)
{
Row row = sheet.getRow(i);
int col =row.getPhysicalNumberOfCells();
int colIndex = 1;
int v=0;
for(int j=0;j<col;j++)
{
String content = row.getCell(j).getStringCellValue();
if(!(content == cmp) && !(content.equals("none")))
{
if(!(cmp.equals("none")))
{
System.out.println("content: "+content);
System.out.println("cmp: "+cmp);
v= j;
System.out.println("row : "+i+"colst : "+(colIndex)+"colend : "+v);
if(!( v-colIndex == 0) && v>0)
{
System.out.println("row : "+i+"colst : "+(colIndex)+"colend : "+v);
sheet.addMergedRegion(new CellRangeAddress(i,i,colIndex-1,v-1));
System.out.println("merged");
}
}
}
if(!(content == cmp))
{
colIndex = v+1;
}
cmp = content;
}
}
FileOutputStream excelOutputStream = new FileOutputStream(
"file.xls");
wb.write(excelOutputStream);
excelOutputStream.close();
}
I endedup getting the following output :
Can anybody help me get an appropriate output ? The main purpose is to merge the cells with common data in the entire proces.

cannot get a numerical value from the excel cell

public Object[][] dataProviderMethod() throws IOException {
try {
file = new FileInputStream(new File("/Users/nanthakumar/Documents/workspace/Myna_Admin/src/com/myna/testdata/login.xls"));
workbook = new HSSFWorkbook(file);
sheet = workbook.getSheetAt(0);
row = sheet.getLastRowNum() + 1;
col = sheet.getRow(0).getLastCellNum();
data = new String[row][col];
for (i = 0; i < row; i++) {
rowvalue = sheet.getRow(i);
for (j = 0; j < col; j++) {
cellValue = rowvalue.getCell(j);
data[i][j] = cellValue.getStringCellValue();
System.out.println("The value is ----->" + data[i][j]);
}
workbook.close();
file.close();
}
} catch (FileNotFoundException nana) {
nana.printStackTrace();
}
return data;
}
This is my code and I tried to add the getnumericalCellvalue() instead of getStringCellValue() but that is not working for me.
first you have to check in the template excel whether the column is number or text.you can get the numerical value if and only if the column is of type number.so change the template excel and try

Categories