Getting nullpointer exception when try to get data from excel ? - java

i Tried to get data from excel in java. if i execute it as normal java program i am getting data from excel and it is getting printed in console.But when i put it my Robotium test project, i am getting null pointer exception(file or directory not found).
public void testCanOpenSettings() throws IOException, Exception {
loginvalid();
}
public void Eula() {
if(solo.searchText("Accept"))
{
System.out.println(" Eula accept");
solo.clickLongOnText("Accept");
}
}
public void loginvalid() throws IOException {
String username;
String password;
solo.sendKey(Solo.MENU);
solo.sleep(3000);
solo.clickLongOnText("Sign In");
solo.sleep(3000);
//solo.clearEditText(0);
username = Readexcel(0,0);
password = Readexcel(0,1);
solo.enterText(0,username);
solo.enterText(1, password);
solo.clickOnCheckBox(0);
solo.clickLongOnText("Sign In");
}
public static String Readexcel(int row,int col) throws IOException {
String filename = "C://Documents//Robo//robo1.xls";
String s = "";
try
{
FileInputStream fis = new FileInputStream(filename);
HSSFWorkbook myWorkBook = new HSSFWorkbook(fis);
HSSFSheet mySheet = myWorkBook.getSheetAt(0);
HSSFRow row1 = mySheet.getRow(row);
HSSFCell cell1 = row1.getCell(col);
s = cell1.getRichStringCellValue().getString();
System.out.println("Cell 1 : "+s);
Log.d("cell value",s );
System.out.println(s);
return s;
}
catch (IOException e) {
e.printStackTrace();strong text
return null;
}
}
}

You are reading the file C://Documents//Robo//robo1.xls, that is stored on your computers HardDrive which your phone of course can't access. You need to put the file on your phone SD-card and use the uri to that location instead:
File storage = Environment.getExternalStorageDirectory() //Returns sd-card
String filename = "robo1.xls"; //file name, may have path separators
File myfile = new File(storage, filename);
//myfile is now a File object that you can use, to get the path, use myfile.getAbsolutePath()

Related

In coding part, if else condition 'else' is not working while writing results in excel using selenium webdriver [API Automation]

Any one please clarify how to resolve this issue.
I am running following code to write a output in excel sheet using Excl utils,
public class AdditionalStorage_Get extends RESTAssuredBase{
//For Reporting
#BeforeTest// - > 2
public void setValues() {
testCaseName = "Validate additionStorage Page Api";
testDescription = "Verify additionStorage - Get request";
nodes = "subscription/additionStorageRequest/f1c547a5-4520-11eb-9a4d-8ea21db6e23d";
category = "REST";
dataFileName = "";
dataFileType = "JSON";
SheetName="APITest";
Expected= "Additional Storage detail should be displayed";
}
#Test
public void additionStorage() throws IOException {
// Post the request
Response response = get("subscription/additionStorageRequest/f1c547a5-4520-11eb-9a4d-8ea21db6e23d");
// Verify the Content type
verifyContentType(response, "JSON");
// Verify the response status code
verifyResponseCode(response, 200);
int status = response.statusCode();
//Verify the response time
verifyResponseTime(response, 2000);
long time = response.time();
enableResponseLog(response);
if(status == 200)
{
Actual = "Request Additional Storage detail is displayed correctly";
ExcelUtils.updateTestResult(SheetName, testDescription, status, time, Actual, Expected, "pass");
}
else
{
Actual="The Response is Not expected";
ExcelUtils.updateTestResult(SheetName, testDescription, status, time, Actual, Expected, "Fail");
}
}
}
Here I am passing my excel sheet to write, While running above script
Its Showing error as "java.lang.NullPointerException" at lib.utils.ExcelUtils.updateTestResult(ExcelUtils.java:40)
public class ExcelUtils extends RESTAssuredBase{
public static void updateTestResult(String SheetName, String testDescription,int code,
Long time,String Actual,String Expected,String Result) throws IOException {
DateTimeFormatter date = DateTimeFormatter.ofPattern("ddMMyyyy");
FileInputStream file = new FileInputStream(new File("./reports/ExcelReport.xlsx"));
XSSFWorkbook workbook = new XSSFWorkbook(file);
XSSFSheet sheet = workbook.getSheet(SheetName);
int totalRow = sheet.getLastRowNum() + 13;
try {
for (int i = 1; i < totalRow; i++)
{
XSSFRow r = sheet.getRow(i);
String ce = r.getCell(1).getStringCellValue();
if (ce.contains(testDescription))
{
r.createCell(2).setCellValue(code);
r.createCell(3).setCellValue(time);
r.createCell(4).setCellValue(Actual);
r.createCell(5).setCellValue(Expected);
r.createCell(6).setCellValue(Result);
file.close();
System.out.println("result updated");
}
}
//file.close();
}
catch (Exception e) {
e.printStackTrace();
}
FileOutputStream outFile = new FileOutputStream(new File("./reports/ExcelReport.xlsx"),false);
workbook.write(outFile);
outFile.close();
}

Unable to return the read the values present in an excel file

I want to return the values present in an excel file but it is returning values like [[Ljava.lang.String;#490ab905. Data is not returning the values like user name. Used jxl and data provider. Even i am not aware of data provider much. Please help me to fetch the accurate values from excel.
Following are my code:
public class excelUtil {
// public String suiteFileName = "/suite.xls";
String testDatafile = "/src/testData/testdata.xls";
// public String testDatafile = "/testdata/Testdata.xls";
#DataProvider
public Object[][] getTestData(String sheetName)
{
//String getTestData(String sheetName, int rowNumber, int colNum) {
// Read Excel
String path = System.getProperty("user.dir") + testDatafile;
Workbook w = null;
File inputWorkbook = new File(path);
// Open workbook
try {
w = Workbook.getWorkbook(inputWorkbook);
} catch (BiffException | IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
// Get the first sheet
Sheet sheet = w.getSheet(sheetName);
//Loop over first 10 column and lines
// Get the first sheet
//Loop over first 10 column and lines
int rowCount = sheet.getRows();
int columnCount = sheet.getColumns();
Object[][] data = new String[rowCount-1][columnCount];
for(int i=1;i<rowCount;i++)
{
Cell cell = sheet.getCell(0, i);
String value = cell.getContents().toString();
System.out.println(value);
data[i-1][0]= value.toString();
System.out.println(data[i-1][0]);
cell = sheet.getCell(1, i);
value = cell.getContents().toString();
data[i-1][1]= value.toString();
}
w.close();
//System.out.println(value);
System.out.println(data);
return data;
}
public static WebDriver driver ;
#Test(dataProvider = "getTestData")
public void OrpakLoginTest(Object username, Object password) {
driver = new FirefoxDriver();
driver.get("http:orpakqa.commdel.com");
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(20, TimeUnit.SECONDS);
Loginelements lg = new Loginelements();
WebElement element_UserName = lg.getOrpakUserNameField(driver);
element_UserName.sendKeys(username.toString());
WebElement element_Password = lg.getOrpakPasswordField(driver);
element_Password.sendKeys(password.toString());
//WebElement element_LoginBtn = lg.getOrpakLoginButton(driver);
//element_LoginBtn.click();
}
Use POI Jars
https://poi.apache.org/download.html
Below code is working for me:-
public String getXLcellValue(String xlpath, String sheetName, int rowNum, int cellNum)
{
try{
FileInputStream fis=new FileInputStream(xlpath);
Workbook wb=WorkbookFactory.create(fis);
Log.info("Get the value from the cell(getXLcellValue)");
return wb.getSheet(sheetName).getRow(rowNum).getCell(cellNum).getStringCellValue();
}
catch(Exception ex)
{
Log.info("Error in getXLcellValue ="+ ex.getMessage());
}
return "";
}
xlpath = path of excel file in your system
Sheetname = name of the sheet in excel file
row = row number of username or password
cellnum = cell number of username or password
You can update your code as below and I hope this solution work for you:
import java.io.File;
import jxl.Sheet;
import jxl.Workbook;
import org.openqa.selenium.By;
import org.testng.annotations.BeforeMethod;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
public class ProApp extends OneClass {
Workbook wb;
Sheet sh1;
int numrow;
String username;
String password;
#BeforeMethod
public void oneTimeSetUp() throws InterruptedException {
driver.manage().window().maximize();
driver.get("Testing.com");
Thread.sleep(1000);
driver.findElement(By.xpath("//*[#id='app']/div/main/section/ul/li[1]/a")).click();
Thread.sleep(1000);
}
#Test(dataProvider="testdata")
public void testFireFox(String uname,String password1) throws InterruptedException
{
driver.findElement(By.xpath("//input[#name='username']")).clear();
Thread.sleep(1000);
driver.findElement(By.xpath("//input[#name='username']")).sendKeys(uname);
Thread.sleep(1000);
driver.findElement(By.xpath("//input[#name='password']")).clear();
Thread.sleep(1000);
driver.findElement(By.xpath("//input[#name='password']")).sendKeys(password1);
Thread.sleep(1000);
driver.findElement(By.xpath("//button[#name='loginButton']")).click();
Thread.sleep(1000);
}
#DataProvider(name="testdata")
public Object[][] TestDataFeed(){
try {
// load workbook
wb=Workbook.getWorkbook(new File("C://File//Book2.xls"));
// load sheet in my case I am referring to first sheet only
sh1= wb.getSheet(0);
// get number of rows so that we can run loop based on this
numrow= sh1.getRows();
}
catch (Exception e)
{
e.printStackTrace();
}
// Create 2 D array and pass row and columns
Object [][] logindata=new Object[numrow][sh1.getColumns()];
// This will run a loop and each iteration it will fetch new row
for(int i=0;i<numrow;i++){
// Fetch first row username
logindata[i][0]=sh1.getCell(0,i).getContents();
// Fetch first row password
logindata[i][1]=sh1.getCell(1,i).getContents();
}
// Return 2d array object so that test script can use the same
return logindata;
}
}

How to write excel using Apache POI with TestNG dataProvider

I am working with hybrid framework, in these for writing an excel sheet I am using Apache-poi library by data provider.
I want my code in these way that by using it I can read and write my excel sheet in which test cases has been written and according to that cases it set their status.
Currently when I am executing my code it skipped the login method. Actually I am beginner in it and try to using it for read and write the excel, can anyone please help me to resolved the problem?
public class HybridExecuteTest {
private static final String BROWSER_PATH = "D:\\abc\\setup\\FFinstalled\\firefox.exe";
private static XSSFWorkbook ExcelWBook;
private static XSSFSheet ExcelWSheet;
private static XSSFCell Cell;
private static XSSFRow Row;
WebDriver webdriver = null;
#Test(dataProvider = "hybridData")
public void testLogin(String testcaseName, String keyword,
String objectName, String objectType, String value)
throws Exception {
// TODO Auto-generated method stub
if (testcaseName != null && testcaseName.length() != 0) {
// webdriver=new FirefoxDriver();
File file = new File(BROWSER_PATH);
FirefoxBinary fb = new FirefoxBinary(file);
webdriver = new FirefoxDriver(fb, new FirefoxProfile());
}
ReadObject object = new ReadObject();
Properties allObjects = object.getObjectRepository();
UIOperation operation = new UIOperation(webdriver);
// Call perform function to perform operation on UI
operation.perform(allObjects, keyword, objectName, objectType, value);
}
#DataProvider(name = "hybridData")
// This method is to set the File path and to open the Excel file, Pass Excel Path and Sheetname as Arguments to this method
public Object[][] setExcelFile(String filePath, String fileName, String sheetName) throws Exception {
Object object[][] = null;
try {
File file = new File(filePath + "\\" + fileName);
// Open the Excel file
FileInputStream ExcelFile = new FileInputStream(file);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(sheetName);
} catch (Exception e) {throw (e);}
return object;
}
// This method is to read the test data from the Excel cell, in this we are passing parameters as Row num and Col num
public String getCellData(int RowNum, int ColNum) throws Exception {
try {
Cell = ExcelWSheet.getRow(RowNum).getCell(ColNum);
String CellData = Cell.getStringCellValue();
return CellData;
} catch (Exception e) {
return "";
}
}
// This method is to write in the Excel cell, Row num and Col num are the parameters
public String setCellData(String Result, int RowNum, int ColNum,String filePath, String fileName) throws Exception {
try {
Row = ExcelWSheet.getRow(RowNum);
Cell = Row.getCell(ColNum, Row.RETURN_BLANK_AS_NULL);
if (Cell == null) {
Cell = Row.createCell(ColNum);
Cell.setCellValue(Result);
} else {
Cell.setCellValue(Result);
}
// Constant variables Test Data path and Test Data file name
File file = new File(filePath + "\\" + fileName);
// Open the Excel file
FileOutputStream ExcelFile = new FileOutputStream(file);
ExcelWBook.write(ExcelFile);
} catch (Exception e) {
throw (e);
}
return null;
}
}
Console:
SKIPPED: testLogin
org.testng.TestNGException:
Some DataProvider public java.lang.Object[][] testCases.HybridExecuteTest.setExcelFile(java.lang.String,java.lang.String,java.lang.String) throws java.lang.Exception parameters unresolved: at 1 type class java.lang.String
at 2 type class java.lang.String
at 3 type class java.lang.String
Note: I have go through the tutorial of Apache poi and normally I understand how to write but in framework I am stuck. Please help in these.
You have tried to pass parameters to dataprovider, this is not supported.declare String filePath, String fileName, String sheetName as class level variables and then access them from the method.
String filePath="something"; String fileName="something"; String sheetName ="something";
#DataProvider(name = "hybridData")
public Object[][] setExcelFile() throws Exception {
Object object[][] = null;
try {
File file = new File(filePath + "\\" + fileName);
// Open the Excel file
FileInputStream ExcelFile = new FileInputStream(file);
// Access the required test data sheet
ExcelWBook = new XSSFWorkbook(ExcelFile);
ExcelWSheet = ExcelWBook.getSheet(sheetName);
} catch (Exception e) {throw (e);}
return object;
}
Another problem that you will face is that you are not assigning anything to object[][] before returning it.

Apache POI event API Update existing Excel sheet

I have large excel file with several worksheets.
I want to process just one sheet in file...Read value from two columns and update two columns.
Using this code, I am able to read data from sheet.But unable to figure out, how to save output back.
public class ExcelFunctions {
private class ExcelData implements SheetContentsHandler {
private Record rec ;
public void startRow(int rowNum) {
rec = new Record();
output.put("R"+rowNum, rec);
}
public void endRow(int rowNum) {
}
public void cell(String cellReference, String formattedValue,
XSSFComment comment) {
int thisCol = (new CellReference(cellReference)).getCol();
if(thisCol==7){
try {
rec.setK1(formattedValue);
} catch (Exception e) {
}
}
if(thisCol==8){
try {
rec.setK2(formattedValue);
} catch (Exception e) {
}
}
if(thisCol == 27){
String key = rec.full_key();
System.out.println(key);
///////Process Matched Key...get Data
//////Set value to column 27
}
if(thisCol == 28){
String key = rec.full_key();
System.out.println(key);
///////Process Matched Key...get Data
//////Set value to column 28
}
}
public void headerFooter(String text, boolean isHeader, String tagName) {
}
}
///////////////////////////////////////
private final OPCPackage xlsxPackage;
private final Map<String, Record> output;
public ExcelFunctions(OPCPackage pkg, Map<String, Record> output) {
this.xlsxPackage = pkg;
this.output = output;
}
public void processSheet(
StylesTable styles,
ReadOnlySharedStringsTable strings,
SheetContentsHandler sheetHandler,
InputStream sheetInputStream)
throws IOException, ParserConfigurationException, SAXException {
DataFormatter formatter = new DataFormatter();
InputSource sheetSource = new InputSource(sheetInputStream);
try {
XMLReader sheetParser = SAXHelper.newXMLReader();
ContentHandler handler = new XSSFSheetXMLHandler(
styles, null, strings, sheetHandler, formatter, false);
sheetParser.setContentHandler(handler);
sheetParser.parse(sheetSource);
} catch(ParserConfigurationException e) {
throw new RuntimeException("SAX parser appears to be broken - " + e.getMessage());
}
}
public void process()
throws IOException, OpenXML4JException, ParserConfigurationException, SAXException {
ReadOnlySharedStringsTable strings = new ReadOnlySharedStringsTable(this.xlsxPackage);
XSSFReader xssfReader = new XSSFReader(this.xlsxPackage);
StylesTable styles = xssfReader.getStylesTable();
XSSFReader.SheetIterator iter = (XSSFReader.SheetIterator) xssfReader.getSheetsData();
boolean found = false;
while (iter.hasNext() && !found) {
InputStream stream = iter.next();
String sheetName = iter.getSheetName();
if(sheetName.equals("All Notes") ){
processSheet(styles, strings, new ExcelData(), stream);
found = true;
}
stream.close();
}
}
#SuppressWarnings("unused")
public static void main(String[] args) throws Exception {
File xlsxFile = new File("C:\\Users\\admin\\Downloads\\Unique Name Macro\\big.xlsm");
if (!xlsxFile.exists()) {
System.err.println("Not found or not a file: " + xlsxFile.getPath());
return;
}
// The package open is instantaneous, as it should be.
OPCPackage p = OPCPackage.open(xlsxFile.getPath(), PackageAccess.READ_WRITE);
Map<String, Record> output = new HashMap<String, Record>();
ExcelFunctions xlFunctions = new ExcelFunctions(p, output);
xlFunctions.process();
p.close();
if (output != null){
for(Record rec : output.values()){
System.out.println(rec.full_key());
}
}
}
}
File is very large and I only want to use Event API.
I have successfully tested Using this code.
But this loads Whole file in memory(causing application to crash)...While I only need to edit One sheet.
public static void saveToExcel(String ofn, Map<String, Record> data) {
FileInputStream infile;
try {
infile = new FileInputStream(new File("C:\\Users\\admin\\Downloads\\Unique Name Macro\\big.xlsm"));
XSSFWorkbook workbook = new XSSFWorkbook (infile);
XSSFSheet sheet = workbook.getSheet("All Notes");
for(Record rec : output.values()){
Row dataRow = rec.getRow(rev.getRownum-1);
setCellValue(dataRow, 26, "SomeValue");
setCellValue(dataRow, 27, "SomeValue");
}
FileOutputStream out = new FileOutputStream(new File(ofn));
workbook.write(out);
infile.close();
out.close();
workbook.close();
}
catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
private static void setCellValue(Row row,int col, String value){
Cell c0 = row.getCell(col);
if (c0 == null){
c0 = row.createCell(col);
}
c0.setCellValue(value);
}
I don't think there is anything provided in POI out of the box which allows to do that.
Therefore you might be better off doing this by unzipping the XLSX/XLSM file (they are actually a bunch of xml-files inside a zip) and reading the xml-files as text-files or with a normal XML Parser so that you can easily write out the changed file again to produce the XLSX/XLSM file again.

how to enhance this java class that reads xls file using POI and JXL?

I am currently using POI to read excel file and it is working great except it can't read xls files with older format (BIFF5/ office 95) to resolve this I am catching OldExcelFormatException and in this case call a function that will read the xls file using jxl. What I want to achieve is to write the same code but without catching the exception. Here is the current working code:
public void translate() throws IOException, CmpException
{
ArrayList<String> row = null;
try
{
// create a new org.apache.poi.poifs.filesystem.Filesystem
POIFSFileSystem poifs = new POIFSFileSystem(fin);
w = new HSSFWorkbook(poifs);
}
catch (OldExcelFormatException e) // OldExcelFormatException
{
w = null;
System.out.println("OldExcelFormatException");
translateBIFF5();
}
catch (Exception e) // Any Exception
{
w = null;
}
if (w != null)
{
// read the excel file using POI
}
}
private void translateBIFF5() throws IOException, CmpException
{
ArrayList<String> row = null;
try
{
jxl_w = Workbook.getWorkbook(excelFile);
}
catch (Exception e) // Any Exception
{
jxl_w = null;
}
if (jxl_w != null)
{
// read the excel file using jxl
}
}
Never mind guys. I found the solution by myself. The trick is to see the workbook name: For excel 95/97, the workbook name is 'Book' while for the new format the workbook name is 'WorkBook'. So here is the piece of coding I have been searching for:
POIFSFileSystem poifs = new POIFSFileSystem(fin);
DirectoryNode directory = poifs.getRoot();
Iterator<Entry> i = directory.getEntries();
while (i.hasNext())
{
Entry e = i.next();
String bookName = e.getName();
if (bookName.equals("Book"))
{
System.out.println("This is an old format");
}
else
{
System.out.println("This is a new format");
}
}

Categories

Resources