Store cell values to Object - automation

I'm currently new to TestNG using java. I'm trying to read the values from an excel using poi apache 4.0
public static void read2dRowExcelFile2(String filePath) throws IOException {
try {
FileInputStream fis = new FileInputStream(new File(filePath));
HSSFWorkbook wb = new HSSFWorkbook(fis);
HSSFSheet sheet = wb.getSheet("PerLocation");
Object[][] tableArr = new String[sheet.getLastRowNum() + 1][];
int arrNo1 = 0;
for (int i = 1; i <= sheet.getLastRowNum(); i++) {
Row row = sheet.getRow(i);
int arrNo2 = 0;
for (int j = 0; j < row.getLastCellNum(); j++) {
String cellValue = row.getCell(j).getStringCellValue();
System.out.println(acellValue);
//tableArr[arrNo1][arrNo2] = cellValue;
System.out.println("test");
arrNo2++;
}
arrNo1++;
}
wb.close();
} catch (Exception e) {
e.printStackTrace();
}
}
Code above displays the values on the console. My goal is to store those values to an Object. Something like [{London, Blue},{Tokyo,Yellow},{Manila,Red}] so I can pass them to a dataProvider
If I run the code above, it displays :
London
BLue
Tokyo
Yellow
Manila
Red
But If i uncomment this line :
//tableArr[arrNo1][arrNo2] = cellValue;
The output is only :
London
03-08-19 : After I enabled stacktrace, it says : java.lang.NullPointerException
which pertains to this code :
tableArr[arrNo1][arrNo2] = cellValue;

From your code,
Object[][] tableArr = new String[sheet.getLastRowNum() + 1][];
At the time of initialization of array, your are setting size of first dimension but not the second . You need to initialize array for second dimension before you access it.
Refer below example:
public static void main(String[] args) {
//read rows size
int numOfRows = 3;
String[][] tableArr = new String[numOfRows][];
for (int row = 0; row <3; row++) {
//read columns size
int numOfColsInRow = 3;
tableArr[row]=new String[numOfColsInRow];
for (int col = 0; col < 3; col++) {
String cellValue = "cell-" + row+""+col;//read cell value
tableArr[row][col] = cellValue;
}
}
for(String[] row: tableArr) {
System.out.println(Arrays.toString(row));
}
}
Running above code with generate expected output:
[cell-00, cell-01, cell-02]
[cell-10, cell-11, cell-12]
[cell-20, cell-21, cell-22]
To reproduce your problem you can try commenting line which initialize array for second dimension in the code and you will see Exception in thread "main" java.lang.NullPointerException
.
//tableArr[row]=new String[numOfColsInRow];
To avoid all such issues you also can check if any exiting TestNG data-provider extension satisfies your need.

Related

How to find empty rows from excel sheet given by user and delete them in asp.net

public async Task<List<IndiaCIT>> Import(IFormFile file)
{
var list = new List<IndiaCIT>();
using (var stream = new MemoryStream())
{
await file.CopyToAsync(stream);
ExcelPackage.LicenseContext = LicenseContext.NonCommercial;
using (var package=new ExcelPackage(stream))
{
ExcelWorksheet worksheet = package.Workbook.Worksheets[0];
var rowcount = worksheet.Dimension.Rows;
for (int row = 1; row <= rowcount; row++)
{
list.Add(new IndiaCIT {
NameCH = worksheet.Cells[row, 1].Value.ToString().Trim(),
City= worksheet.Cells[row, 2].Value.ToString().Trim(),
Age = worksheet.Cells[row, 3].Value.ToString().Trim(),
});
}
}
}
return list;
}
this is controller code and in model class declared the columns name and used it as IndiaCIT list in controller,. I want empty rows to get deleted
This could help:
For each row in the sheet, check if the cell in each column is empty. If so delete it.
var rowcount = worksheet.Dimension.Rows;
var maxColums = worksheet.Dimension.Columns;
for(int row = rowcount; row > 0; row--)
{
bool isRowEmpty = true;
for(int column = 1; column <= maxColumns; column++)
{
var cellEntry = worksheet.Cells[row, column].Value.ToString();
if(!string.IsNullOrEmpty(cellEntry)
{
isRowEmpty = false;
break;
}
}
if(!isRowEmpty)
continue;
else
worksheet.DeleteRow(row);
}
I generally use Spire.Xls to handle such problems. It works for me.
public IActionResult Test() {
//init workbook
Workbook workbook = new Workbook();
// load file
workbook.LoadFromFile("11.xlsx");
// get the first sheet
Worksheet sheet = workbook.Worksheets[0];
//delete blank row
for (int i = sheet.Rows.Count() - 1; i >= 0; i--)
{
if (sheet.Rows[i].IsBlank)
{
sheet.DeleteRow(i + 1);
}
}
//delete blank column
for (int j = sheet.Columns.Count() - 1; j >= 0; j--)
{
if (sheet.Columns[j].IsBlank)
{
sheet.DeleteColumn(j + 1);
}
}
//save as a new xls file
workbook.SaveToFile("new.xlsx", ExcelVersion.Version2016);
return Ok();
}

Why doesn't my number sequence print from the 2d arraylist correctly?

I cannot get the loop to work in the buildDimArray method to store the number combinations "11+11", "11+12", "11+21", "11+22", "12+11", "12+12", "12+21", "12+22", "21+11", "21+12", "21+21", "21+22", "22+11", "22+12", "22+21", and "22+22" into the 2d arraylist with each expression going into one column of the index dimBase-1 row. The loop may work for other people, but for some reason mine isn't functioning correctly. The JVM sees the if dimBase==1 condition, but refuses to check the other conditions. The "WTF" not being printed as a result from the buildDimArray method. If dimBase=1, it prints successfully, but doesn't for the other integers. The dimBase==3 condition needs a loop eventually. The "WTF" is for illustrative purposes. I could get away with a 1d arraylist, but in the future I will likely need the 2d arraylist once the program is completed.
package jordanNumberApp;
import java.util.Scanner;
import java.util.ArrayList;
/*
* Dev Wills
* Purpose: This code contains some methods that aren't developed. This program is supposed to
* store all possible number combinations from numbers 1-dimBase for the math expression
* "##+##" into a 2d arraylist at index row dimBase-1 and the columns storing the
* individual combinations. After storing the values in the arraylist, the print method
* pours the contents in order from the arraylist as string values.
*/
public class JordanNumberSystem {
// a-d are digits, assembled as a math expression, stored in outcomeOutput, outcomeAnswer
public static int dimBase, outcomeAnswer, a, b, c, d;
public static String inputOutcome, outcomeOutput;
public static final int NUM_OF_DIMENSIONS = 9; //Eventually # combinations go up to 9
public static ArrayList<ArrayList<String>> dimBaseArray;
public static Scanner keyboard;
/*
* Constructor for JordanNumber System
* accepts no parameters
*/
public JordanNumberSystem() // Defunct constructor
{
// Declare and Initialize public variables
this.dimBase = dimBase;
this.outcomeOutput = outcomeOutput;
this.outcomeAnswer = outcomeAnswer;
}
// Set all values of variable values
public static void setAllValues()
{
// Initialize
dimBase = 1;
outcomeAnswer = 22; // variables not used for now
outcomeOutput = "1"; // variables not used for now
//a = 1;
//b = 1;
//c = 1;
//d = 1;
dimBaseArray = new ArrayList<ArrayList<String>>();
keyboard = new Scanner(System.in);
}
public static void buildDimArray(int dim)
{
dimBase = dim;
try
{
//create first row
dimBaseArray.add(dimBase-1, new ArrayList<String>());
if( dimBase == 1)
{
a = b = c = d = dimBase ;
dimBaseArray.get(0).add(a+""+b+"+"+c+""+d);
System.out.println("WTF"); // SHOWS
}
else if (dimBase == 2)
{ // dim = 2
a = b = c = d = 1 ;
System.out.println("WTF"); // doesn't show
// dimBaseArray.get(dimBase-1).add(a+""+b+"+"+c+""+d);
for( int i = 1 ; i <= dim ; i++)
a=i;
for( int j = 1 ; j <= dim ; j++)
b=j;
for( int k = 1 ; k <= dim ; k++)
c=k;
for( int l = 1 ; l <= dim ; l++)
{
d=l;
dimBaseArray.get(dim-1).add(a+""+b+"+"+c+""+d);
}
}
else if (dimBase == 3)
{
a = b = c = d = dimBase;
dimBaseArray.get(2).add(a+""+b+"+"+c+""+d);
System.out.println("WTF");
}
}catch (IndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
}
}
public static void printArray(int num) // Prints the contents of the array
{ // Fixing the printing method
try
{
int i = num-1;
for( String string : dimBaseArray.get(i))
{
System.out.println(string);
System.out.println("");
}
} catch (IndexOutOfBoundsException e)
{
System.out.println(e.getMessage());
}
}
public static void main(String[] args) throws java.lang.IndexOutOfBoundsException
{
setAllValues(); // sets the initial a,b,c,d values and dimBase, initializes 2d arraylist
// Get the Dimension Base number
System.out.println("Enter Dimension Base Number. Input an integer: ");
int dimBaseInput = keyboard.nextInt(); // Receives integer
dimBase = dimBaseInput;
if( dimBase != 1 && dimBase != 2 && dimBase != 3)
{// Error checking
System.out.println("invalid Dimension Base Number should be 1 or 2 ");
System.exit(1);
}
// Build the arraylist, print, clear, exit
buildDimArray(dimBase);
printArray(dimBase);
dimBaseArray.clear();
System.exit(1);
}
}// End of class

Why the last empty row has been pulled as an additional test with null values in selenium apache POI

I have four rows in an excel, first row is for the heading and rest of the three rows has values in it. I have entered the code in a way to avoid the header and read the rows which contains values only. However instead of fetching only three rows it comes with one additional null value rows as below, Why it is fetching the null values did I miss anything? Find the code and error message.
Message
PASSED: testShipment("Mumbai", "New York", "18000", "10000", "20000")
PASSED: testShipment("Mumbai", "Cochin", "2000", "30000", "5000")
PASSED: testShipment("Cochin", "Farah", "16000", "18000", "19000")
FAILED: testShipment(null, null, null, null, null)
Code
int TotalCol = sh.getRow(0).getLastCellNum();
int Totalrows = sh.getLastRowNum()+1;
String[][] data = new String[Totalrows][TotalCol];
DataFormatter formatter = new DataFormatter(); // creating formatter using the default locale
for (int i = 1; i < Totalrows; i++) {
Row r = sh.getRow(i);
for (int j = 0; j < TotalCol; j++) {
Cell c = r.getCell(j);
try {
if (c.getCellType() == Cell.CELL_TYPE_STRING) {
String j_username = formatter.formatCellValue(c);
data[i][j] = j_username;
System.out.println("data[i][j]" + data[i][j]);
} else {
data[i][j] = String.valueOf(c.getNumericCellValue());
String j_username = formatter.formatCellValue(c);
data[i][j] = j_username;
System.out.println("data[i][j] numeric val" + data[i][j]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Try with the below code like checking null condition
for (int k = 1; k <= totalRows; k++) {
String testCaseID = sheet.getRow(k).getCell(0).getStringCellValue();
if (testCaseID.equalsIgnoreCase(tcID)) {
for (int l = 1; l < totalCols; l++) {
String testData_FieldName = sheet.getRow(0).getCell(l).getStringCellValue();
if (testData_FieldName.equalsIgnoreCase(header)) {
cell = sheet.getRow(k).getCell(l);
if (cell != null) {
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:// numeric value in excel
result = cell.getNumericCellValue();
break;
case Cell.CELL_TYPE_STRING: // string value in excel
result = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_BOOLEAN: // boolean value in excel
result = cell.getBooleanCellValue();
break;
case Cell.CELL_TYPE_BLANK: // blank value in excel
result = cell.getStringCellValue();
break;
case Cell.CELL_TYPE_ERROR: // Error value in excel
result = cell.getErrorCellValue() + "";
break;
default:
throw new CustomException("The cell data type is invalid");
}
}
}
}
k = totalRows + 1;
}
}
You need to change either the data array declaration part or Totalrows calculation part. Currently, you have created 4 rows object and only 3 rows values are assigned and hence 4th row values are holding null value.
String[][] data = new String[Totalrows][TotalCol];
In your string array, you are not persisting the header value and storing only values. So, please modify your code with any one of the below options (I would suggest you to use option 1)
Option 1:
Remove the +1 from Totalrows variable and add the equal condition in your first for loop
//Removed the +1
int Totalrows = sh.getLastRowNum();
String[][] data = new String[Totalrows][TotalCol];
DataFormatter formatter = new DataFormatter(); // creating formatter using the default locale
//Condition is modified as i <= Totalrows
for (int i = 1; i <= Totalrows; i++) {
Option 2:
Change the data[][] declaration part
int Totalrows = sh.getLastRowNum()+1;
String[][] data = new String[Totalrows-1][TotalCol];
Here is the code that works, thanks to everyone for helping on this!
int TotalCol = sh.getRow(0).getLastCellNum();
int Totalrows = sh.getLastRowNum()+1;
//Entering minus one(-1) during data declaration ignores the first row as first row is a header
String[][] data = new String[Totalrows-1][TotalCol];
DataFormatter formatter = new DataFormatter(); // creating formatter using the default locale
for (int i = 1; i <Totalrows; i++) {
Row r = sh.getRow(i);
for (int j = 0; j < TotalCol; j++) {
Cell c = r.getCell(j);
try {
if (c.getCellType() == Cell.CELL_TYPE_STRING) {
String j_username = formatter.formatCellValue(c);
//Adding minus on(data[i-1]) helps to read the first cell which is (0,1), in this case (0,1) would not read the header since we have skipping the header from the table in the previous step on top, therefore the actual table starts from the second row.
data[i-1][j] = j_username;
System.out.println("data[i-1][j]" + data[i-1][j]);
} else {
data[i-1][j] = String.valueOf(c.getNumericCellValue());
String j_username = formatter.formatCellValue(c);
data[i-1][j] = j_username;
System.out.println("data[i-1][j] numeric val" + data[i-1][j]);
}
} catch (Exception e) {
e.printStackTrace();
}
}
"

Reading 3rd data data from excel using HSSF

I am trying to read the excel data, there are 2 data exist in the excel but my program is trying to read 3rd data which is null. Can some one please help me on this. below is my code.
public static Object[][] readExcel(String filePath, String sheetName)
throws IOException {
String[][] sheetData = null;
FileInputStream inputStream = new FileInputStream(filePath);
workBook = new HSSFWorkbook(inputStream);
sheet = workBook.getSheet(sheetName);
int k, l;
int rowCount = sheet.getLastRowNum()-sheet.getFirstRowNum();
System.out.println(rowCount);
int readRowCount = sheet.getFirstRowNum();
Row r = sheet.getRow(1);
int totalCol = r.getLastCellNum();
System.out.println(totalCol);
sheetData = new String[rowCount + 1][totalCol];
k = 0;
for (int i = readRowCount + 1; i <= rowCount; i++, k++) {
l = 0;
for (int j = 0; j < totalCol; j++, l++) {
try {
sheetData[k][l] = getCellData(i, j);
System.out.println(sheetData[k][l]);
} catch (Exception e) {
e.printStackTrace();
}
}
}
return (sheetData);
}
public static String getCellData(int RowNum, int ColNum) throws Exception {
try {
Cell = sheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
} catch (Exception e) {
return "";
}
}
enter image description here

Gettinh NULL pointer while tryying to write into an excel

This is my Util function :
// Method to write into an XL
public static void writeXL(String fPath, String fSheet, String[][] xData) throws Exception{
File outFile = new File(fPath);
HSSFWorkbook wb = new HSSFWorkbook();
HSSFSheet osheet = wb.createSheet(fSheet);
int xR_TS = xData.length;
// System.out.println(xR_TS);
int xC_TS = xData[0].length;
// System.out.println(xC_TS);
for (int myrow = 0; myrow < xR_TS; myrow++) {
HSSFRow row = osheet.createRow(myrow);
for (int mycol = 0; mycol < xC_TS; mycol++) {
HSSFCell cell = row.createCell(mycol);
cell.setCellType(HSSFCell.CELL_TYPE_STRING);
cell.setCellValue(xData[myrow][mycol]);
}
FileOutputStream fOut = new FileOutputStream(outFile);
wb.write(fOut);
fOut.flush();
fOut.close();
}
}
While I am trying to write into this excel using the below command :
// i is the loop value
xlActualTot[i][5]=PayAmt; // where PayAmt is the value I am capturing from website and storing it in xlActualTot[0][5] (type is String[][])
Utils.writeXL("<filepath>","TestData",xlActualTot);
I am getting the below exception at "xlActualTot[0][5]=PayAmt" this line :
java.lang.NullPointerException
Can you all please suggest why I am getting that error?