Gettinh NULL pointer while tryying to write into an excel - selenium

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?

Related

Selenium - Unable to pick particular rows from TestData excel file

I am trying to build the TestDataReader.java file. My code should pick only the rows which are tagged by the particular testcaseid (For eg: for Test Case 1, it should pick only rows with TC_001, for Test Case 2 it should pick only rows with TC_002) and return the data to the Dataprovider method. With the below attached code, When i pass Test Case ID as TC_002, it is putting null in the testData[rowNum][0] column for rows with TC_001.
My expectation is that i should get rows only for TC_002. it should not process for TC_001.
Please suggest what is incorrect in this code.
Below is my TestDatareader class:
package com.automation.website.kaspick.utils;
import java.io.FileInputStream;
import java.io.IOException;
import java.nio.file.Paths;
import java.util.HashMap;
import org.apache.poi.xssf.usermodel.XSSFCell;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class TestDataReader {
XSSFWorkbook xlWorkbook = null;
XSSFSheet sheet = null;
XSSFRow row = null;
XSSFCell cell = null;
String currentDir = Paths.get("").toAbsolutePath().toString();
String testDataFileName = "\\TestData\\TestData.xlsx";
String sheetName = null;
String xlFilePath = currentDir + testDataFileName;
public Object[][] readTestData(String sheetName, String testCaseID) throws IOException {
String rowHeader = null;
String columnValue = null;
FileInputStream fileInputStream = new FileInputStream(xlFilePath);
xlWorkbook = new XSSFWorkbook(fileInputStream);
sheet = xlWorkbook.getSheet(sheetName);
int rowCount = sheet.getLastRowNum();
Object[][] testData = new Object[rowCount][1]; // This object is created to store the MapData as an object for
// DataProvider
if (sheet.getSheetName().equalsIgnoreCase(sheetName)) {
for (int rowNum = 0; rowNum < rowCount; rowNum++) {
HashMap<Object, Object> testDataInEachRow = new HashMap<Object, Object>();
row = sheet.getRow(rowNum + 1); // Since the first row will be header, parse from the second row
int columnCount = row.getLastCellNum();
for (int colNum = 0; colNum < columnCount; colNum++) {
rowHeader = sheet.getRow(0).getCell(colNum).toString();
if(colNum==0 && !row.getCell(colNum).toString().equalsIgnoreCase(testCaseID)) {
break;
}
if (row.getCell(colNum) != null) {
columnValue = row.getCell(colNum).toString();
} else {
columnValue = "";
}
testDataInEachRow.put(rowHeader, columnValue);
}
}
testData[rowNum][0] = testDataInEachRow;
}
return testData;
}
}
Below is my Test Data. I have masked the data
[TestData.xlsx][1]
[1]: https://i.stack.imgur.com/h6cMf.png

Store cell values to Object

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.

NullReference Error while reading xlsx EPPlus Core

I'm trying to upload an excel file with EPPlus. I'ts like my excel file was empty, but it has content inside.
Im getting this error:
worksheet.Dimension.Rows = 'worksheet.Dimension.Rows' threw an exception of type 'System.NullReferenceException'
on this line: int rowCount = worksheet.Dimension.Rows;
[HttpPost("Excel")]
public string UploadExcel(IFormFile file)
{
var filePath = Path.GetTempFileName();
FileInfo excel = new FileInfo(filePath);
using (ExcelPackage package = new ExcelPackage(excel))
{
StringBuilder sb = new StringBuilder();
ExcelWorksheet worksheet = package.Workbook.Worksheets[file.FileName];
int rowCount = worksheet.Dimension.Rows;
int ColCount = worksheet.Dimension.Columns;
bool bHeaderRow = true;
for (int row = 1; row <= rowCount; row++)
{
for (int col = 1; col <= ColCount; col++)
{
if (bHeaderRow)
{
sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
}
else
{
sb.Append(worksheet.Cells[row, col].Value.ToString() + "\t");
}
}
sb.Append(Environment.NewLine);
}
return sb.ToString();
}
Can you verify that the workshseets are being loaded?
//examine in the debugger to make sure the worksheet you want is loaded
var worksheets = package.Workbook.Worksheets.ToList();
If that doesn't work, can you try one of these?
var worksheet = package.Workbook.Worksheets[0];
var worksheetFirst = package.Workbook.Worksheets.First();
UPDATE:
The real error is that you are trying to read a temp file with var filePath = Path.GetTempFileName();. You need to read an actual excel file. For example, you could use Path.GetFullPath("path/to/the/excel/file.xls");

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

"Out Of Memory" exception while exporting from SQL Server to Excel, using EPPlus library

I'm using the EPPlus .NET library in order to export data from SQL Server to an Excel file.
I'm using the SqlConnection class to read the data. For every row of the SqlDataReader cursor, I iterate through all the excel cells for the corresponding row, and enter the data from the reader.
The issue is that I'm getting an "out of memory" error when im using this function for large tables. I need a method to create some kind of a buffer inside the Read CURSOR.
A concise code example:
Dim sqlConnection As SqlConnection = New SqlConnection()
sqlConnection.ConnectionString = sqlConnectionString.ConnectionString 'connectionstring built before
Dim query As SqlCommand = New SqlCommand(query...)
Dim newFileStream As New FileStream("c:\junk\test.xlsx", System.IO.FileMode.Create,System.IO.FileAccess.ReadWrite)
Using excelApp As New ExcelPackage(newFileStream)
sqlConnection.Open()
Dim sqlReader As SqlDataReader = query.ExecuteReader()
Dim numOfColumns As Byte = sqlReader.FieldCount()
Dim rowNumber As Integer = 1
While sqlReader.Read()
Dim currentColumn As Byte
For currentColumn = 1 To numOfColumns
ws.Cells(rowNumber,currentColumn).Value = sqlReader.Item(currentColumn - 1)
Next
rowNumber += 1
End While
excelApp.Save()
End Using
newFileStream.Close()
Since you will have to split the files anyway when you hit Excel's limits, here's some code that reads from the database in chunks into multiple Excel files:
static class Program
{
private static string _dataSource;
private static string _database;
private static string _table;
private static string _outputPath;
private static int _batchSize;
public static void Main()
{
try
{
_dataSource = ConfigurationManager.AppSettings["DataSource"];
_database = ConfigurationManager.AppSettings["Database"];
_table = ConfigurationManager.AppSettings["Table"];
_outputPath = ConfigurationManager.AppSettings["OutputPath"];
_batchSize = int.Parse(ConfigurationManager.AppSettings["BatchSize"]);
CreateExcel(_dataSource, _database, _table, _outputPath, "SELECT * FROM " + _table);
}
catch (Exception e)
{
Console.WriteLine(e);
}
Console.WriteLine("All done!");
}
public static void CreateExcel(string dataSource, string databaseName, string tableName, string outputFilePath, string queryNoParameters)
{
var sqlConnectionString = new SqlConnectionStringBuilder
{
DataSource = dataSource,
InitialCatalog = databaseName,
IntegratedSecurity = true
};
using (var connection = new SqlConnection(sqlConnectionString.ConnectionString))
{
connection.Open();
using (var command = new SqlCommand { Connection = connection, CommandType = CommandType.Text, CommandText = queryNoParameters })
using (var sqlReader = command.ExecuteReader())
{
int i = 0;
while (WriteExcelFile(tableName, GetFileInfo(databaseName, tableName, outputFilePath, i++),
sqlReader, sqlReader.FieldCount, _batchSize))
{
Console.WriteLine("Reading next batch...");
}
}
}
}
private static bool WriteExcelFile(string tableName, FileInfo fileInfo, IDataReader sqlReader, int numOfColumns, int count)
{
using (var excelPackage = new ExcelPackage(fileInfo))
{
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets.Add(tableName);
Console.WriteLine("Populating header row...");
for (var currentColumn = 1; currentColumn <= numOfColumns; currentColumn++)
{
worksheet.Cells[1, currentColumn].Value = sqlReader.GetName(currentColumn - 1);
worksheet.Column(currentColumn).Style.Numberformat.Format =
TranslateSystemtypeToExceltype(sqlReader.GetFieldType(currentColumn - 1));
}
Console.WriteLine("Reading data rows...");
int rowNumber = 2;
while (rowNumber <= count + 1 && sqlReader.Read())
{
for (var currentColumn = 1; currentColumn <= numOfColumns; currentColumn++)
worksheet.Cells[rowNumber, currentColumn].Value = sqlReader[currentColumn - 1];
rowNumber++;
}
if (rowNumber == 2) //nothing read
{
Console.WriteLine("Nothing to read, reached end of table!");
return false;
}
Console.WriteLine("Saving Excel file...");
excelPackage.Save();
return rowNumber == count + 2; //in which case we want to read more
}
}
private static FileInfo GetFileInfo(string databaseName, string tableName, string outputFilePath, int i)
{
return new FileInfo(Path.Combine(outputFilePath,
Path.ChangeExtension(
string.Format("{0}_{1}_{2}", databaseName, tableName.Replace('.', '-'), i), "xlsx")));
}
public static string TranslateSystemtypeToExceltype(Type sysType)
{
if (sysType == typeof(string))
return "#";
if (sysType == typeof(DateTime))
return "dd/MM/YYYY";
if (sysType == typeof(Decimal))
return "0.000";
if (sysType == typeof(bool))
return "#";
if (sysType == typeof(int))
return "0";
if (sysType == typeof(short))
return "0";
if (sysType == typeof(double))
return "0.000";
return "General";
}
}