How to save excel data to json file? - java

When I try to save excel data in JSON file under resource folder. I am getting Null pointer exception when I hit send in postman. Not sure if the code is okay or anyone can refer any code for saving excel file in json format.
import java.io.FileWriter;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.json.simple.JSONObject;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;
import com.google.gson.Gson;
#RestController
public class ExcelController {
#PostMapping("excel")
public String getExcel(#RequestParam("file") MultipartFile file) {
excel2Json(file);
return "Success";
}
public void excel2Json(MultipartFile file) {
try {
XSSFWorkbook workBook = new XSSFWorkbook(file.getInputStream());
XSSFSheet workSheet = workBook.getSheetAt(0);
List<JSONObject> dataList = new ArrayList<>();
XSSFRow header = workSheet.getRow(0);
for(int i=1;i<workSheet.getPhysicalNumberOfRows();i++) {
XSSFRow row = workSheet.getRow(i);
JSONObject rowJsonObject = new JSONObject();
for(int j=0; j<row.getPhysicalNumberOfCells();j++) {
String columnName = header.getCell(j).toString();
String columnValue = row.getCell(j).toString();
rowJsonObject.put(columnName, columnValue);
}
dataList.add(rowJsonObject);
}
System.out.println(dataList);
writeData2JsonFile(dataList);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public void writeData2JsonFile(List<JSONObject> dataList) {
Gson gson = new Gson();
try {
FileWriter file = new FileWriter("D:\\work\\blog-api\\src\\main\\resources\\data.json");
file.write(gson.toJson(dataList));
file.close();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
}
Please let me know why I am getting null pointer exception when I hit the excel file in postman.

Related

I try to retain the input but InvalidFormatException was thrown

I would like to retain the data in the existing excel file.After that then try to output something to this file.But I got an error.
I have been searching the answer but none of it matches my situation.
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class TryHyperlink{
public static void main(String[] args) {
File in = new File("D:\\Test1.xlsx");
try {
FileInputStream fin = new FileInputStream(in);
//read input
XSSFWorkbook wb;
wb = new XSSFWorkbook(fin);//The StackTrace shows that the error is here
XSSFSheet sheet = wb.getSheetAt(0);
Iterator<Row> rowItr = sheet.iterator();
//iterate through every row and cell
while(rowItr.hasNext()) {
Row row = rowItr.next();
Iterator<Cell> cellItr = row.iterator();
while(cellItr.hasNext()) {
Cell cell = cellItr.next();
}
}
fin.close();
//close the input stream so output stream can write
FileOutputStream fout = new FileOutputStream(in);
wb.write(fout);
} catch (IOException e) {
e.printStackTrace();
}
}
}
Edit:
After referring to Alex Richter Comment,I closed the output stream and the error gone. Now Another error come out:
WARNING: An illegal reflective access operation has occurred and so on(the link of the photo at the bottom of the question)
package net.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class TryHyperlink{
public static void main(String[] args) {
File in = new File("D:\\penril.xlsx");
try {
FileInputStream fin = new FileInputStream(in);
XSSFWorkbook wb;
wb = new XSSFWorkbook(fin);
XSSFSheet sheet = wb.getSheetAt(0);
Iterator<Row> rowItr = sheet.iterator();
while(rowItr.hasNext()) {
Row row = rowItr.next();
Iterator<Cell> cellItr = row.iterator();
while(cellItr.hasNext()) {
Cell cell = cellItr.next();
cell.setCellValue(cell.getNumericCellValue());
}
}
fin.close();
FileOutputStream fout = new FileOutputStream(in);
wb.write(fout);
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
```package net.excel;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class TryHyperlink{
public static void main(String[] args) {
File in = new File("D:\\penril.xlsx");
try {
FileInputStream fin = new FileInputStream(in);
XSSFWorkbook wb;
wb = new XSSFWorkbook(fin);
XSSFSheet sheet = wb.getSheetAt(0);
Iterator<Row> rowItr = sheet.iterator();
while(rowItr.hasNext()) {
Row row = rowItr.next();
Iterator<Cell> cellItr = row.iterator();
while(cellItr.hasNext()) {
Cell cell = cellItr.next();
cell.setCellValue(cell.getNumericCellValue());
}
}
fin.close();
FileOutputStream fout = new FileOutputStream(in);
wb.write(fout);
fout.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}```
[1]: https://i.stack.imgur.com/WTOn3.png

Unable to write to Excel using Selenium webdriver

I have created a test where I am reading from excel and iterating through a worksheet to process an application in a web portal. This is working as expected.
However I am now trying to write results from the web page into another sheet on the same excel. The test case I am running passes in Eclipse but no data is written to the specified sheet. (I'm also looking to iterate on the results sheet to capture multiple application records, haven't got to that part yet).
Please see below my test script and the methods I have created in an ExcelConfig util sheet. Hoping someone can advise where I'm going wrong, thanks in advance.
Steve
Test Case
package com.htb.puma.uatTests;
import org.junit.Test;
import org.openqa.selenium.WebDriver;
import com.htb.puma.pages.SMcaseHeader;
import com.htb.puma.pages.SMhome;
import com.htb.puma.pages.SMloanDetails;
import com.htb.puma.pages.SMlogin;
import com.htb.puma.pages.SetUpConfig;
import com.htb.puma.util.ExcelConfig;
import org.openqa.selenium.Keys;
import org.openqa.selenium.NoAlertPresentException;
import java.io.File;
import java.io.IOException;
public class THAM_WRITE_Test {
WebDriver driver;
#Test
public void specMortHome() throws NoAlertPresentException, InterruptedException, IOException {
// calling drivers from the SetUpConfig page
driver = SetUpConfig.getChromeDriver();
// driver = SetUpConfig.getFirefoxDriver();
// driver = SetUpConfig.getIEDriver();
String path = new File("src/test/resources/TestData.xlsx").getAbsolutePath();
ExcelConfig excel = new ExcelConfig(path);
int row = 1;
while (excel.getData("PDFRollUp", row, 0) != "") {
String loanAmReq = excel.getNumericData("PDFRollUp", row, 6);
// LOGIN
SMlogin specMortLogin = new SMlogin(driver);
specMortLogin.openSMlogin();
specMortLogin.maximiseWindow();
specMortLogin.enterUsername("OpsAdminAuto");
specMortLogin.enterPassword("AutoOps123!");
specMortLogin.clickSignInBtn();
Thread.sleep(2000);
SMhome specMortHome = new SMhome(driver);
specMortHome.clickTopMC();
Thread.sleep(2000);
SMcaseHeader specMortCaseHeader = new SMcaseHeader(driver);
specMortCaseHeader.clickLoanDetailsTab();
SMloanDetails specMortLoanDetails = new SMloanDetails(driver);
Thread.sleep(2000);
specMortLoanDetails.enterLoanAmReq(Keys.CONTROL + "a"); // PDF
specMortLoanDetails.enterLoanAmReq(loanAmReq); // PDF
String erc = specMortLoanDetails.getERC();
String ltv = specMortLoanDetails.getLTV();
excel.createFile("src/test/resources/TestData.xlsx");
excel.writeStringData("Results", 1, 1, erc);
excel.writeStringData("Results", 1, 2, ltv);
specMortHome.clickUserActionsHomeLM();
specMortHome.clickLogoutHomeLM();
row++;
}
driver.quit();
}
}
Excel Config
package com.htb.puma.util;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.DataFormatter;
import org.apache.poi.ss.usermodel.Font;
import org.apache.poi.ss.usermodel.Row;
public class ExcelConfig {
public XSSFWorkbook wb;
XSSFSheet sheet1;
public ExcelConfig(String Excelpath) {
File src = new File(Excelpath);
try {
FileInputStream fis = new FileInputStream(src);
wb = new XSSFWorkbook(fis);
} catch (Exception e) {
System.out.println("Excel file not loaded");
}
}
// reads the string in the excel file
public String getData(String sheetName, int row, int column) {
sheet1 = wb.getSheet(sheetName);
String data = "";
try {
data = sheet1.getRow(row).getCell(column).getStringCellValue();
} catch (NullPointerException e) {
data = "";
}
return data;
}
// reads the number in the excel file
public String getNumericData(String sheetName, int row, int column) {
sheet1 = wb.getSheet(sheetName);
String data = "";
try {
// data = sheet.getRow(row).getCell(column).getRawValue();
DataFormatter dataFormatter = new DataFormatter();
Cell cell = sheet1.getRow(row).getCell(column);
data = dataFormatter.formatCellValue(cell);
} catch (NullPointerException e) {
data = "";
}
return data;
}
//write string data into excel
public void writeStringData(String sheetName, int row, int column, String data) {
sheet1 = wb.getSheet(sheetName);
Row valueRow = sheet1.getRow(row);
Cell valueCell = valueRow.createCell(column);
if (data.equals("FAILED")) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
//font.setColor(HSSFColor.RED.index);
style.setFont(font);
valueCell.setCellValue(data);
valueCell.setCellStyle(style);
}
valueCell.setCellValue(data);
}
//creates an excel file
public void createFile(String path) {
File src = new File(path);
try {
FileOutputStream outputStream = new FileOutputStream(src);
try {
wb.write(outputStream);
outputStream.close();
} catch (IOException e) {
e.printStackTrace();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
}
}
}
write(java.io.OutputStream stream) is used to write data to the excel file
public void writeStringData(String sheetName, int row, int column, String data) {
try {
sheet1 = wb.getSheet(sheetName);
Row valueRow = sheet1.getRow(row);
Cell valueCell = valueRow.createCell(column);
if (data.equals("FAILED")) {
CellStyle style = wb.createCellStyle();
Font font = wb.createFont();
//font.setColor(HSSFColor.RED.index);
style.setFont(font);
valueCell.setCellValue(data);
valueCell.setCellStyle(style);
}
valueCell.setCellValue(data);
FileOutputStream fout;
fout = new FileOutputStream(new File("<path>"));
//fout = new FileOutputStream("src/test/resources/TestData.xlsx" );
wb.write(fout);
// fout.flush();
wb.close();
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (EncryptedDocumentException e) {
e.printStackTrace();
} catch (NullPointerException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}

Read data from Excel and write to Docx file using java

I have some records with header in my excel sheet.I want to read all the records and write to the docx file along with header using java.Thanks for the helps.
Able to write one excel to other excel file but failed to write in docx file.
I have try this way but the word file is generated as corrupted.
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.*;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Iterator;
public class ExcelReaderDemo {
public static final String SAMPLE_XLSX_FILE_PATH =
"C:/XLXSToDocx/Roaster.xlsm";
public static final String FILE_PATH ="C:/XLXSToDocx/writeExcel.docx";
public static void main(String[] args) throws IOException,
InvalidFormatException {
Workbook workbook = WorkbookFactory.create(new
File(SAMPLE_XLSX_FILE_PATH));
System.out.println("Workbook has " + workbook.getNumberOfSheets() + "
Sheets : ");
Sheet sheet = workbook.getSheetAt(0);
DataFormatter dataFormatter = new DataFormatter();
Iterator<Row> rowIterator = sheet.rowIterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t");
}
try {
FileOutputStream fos = new FileOutputStream(FILE_PATH);
workbook.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println();
}
workbook.close();
}
}
I would suggest to use Apache Poi lib (https://poi.apache.org/)
Rewrite your code like this:
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
public class ExcelReaderDemo {
public static final String SAMPLE_XLSX_FILE_PATH = "C:/XLXSToDocx/Roaster.xlsm";
public static final String FILE_PATH = "C:/XLXSToDocx/writeExcel.docx";
public static void main(String[] args) throws IOException, InvalidFormatException {
Workbook workbook = WorkbookFactory.create(new File(SAMPLE_XLSX_FILE_PATH));
System.out.println("Workbook has " + workbook.getNumberOfSheets() + " Sheets : ");
try {
FileOutputStream fos = new FileOutputStream(FILE_PATH);
workbook.write(fos);
fos.close();
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
System.out.println("DONE !!!");
}
}

Convert avro file into csv in java web application

We have a requirement where we would like to convert an avro file which we download from our third party vendor API in our java web application. I tried going through some of the resources where all i could find was command s to execute with help of avro-tools.jar But i am looking for a way to achieve this within Java web application. Any help greatly appreciated.
You can use avro-tools to read the avro records , get Schema and records from the file
Attaching a rough draft :
I'm using JSON as intermediary ,You can modify it to any format of your choice
import java.io.File;
import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import org.json.CDL;
import org.json.JSONArray;
import org.json.JSONException;
import org.apache.avro.Schema;
import org.apache.avro.Schema.Field;
import org.apache.avro.file.DataFileReader;
import org.apache.avro.generic.GenericData;
import org.apache.avro.generic.GenericDatumReader;
import org.apache.commons.io.FileUtils;
public class AvroToCSV {
public static void readAvro(File file) {
// Read Avro ,parse Schema to get field names and parse it to json
try {
GenericDatumReader<GenericData.Record> datum = new GenericDatumReader<GenericData.Record>();
DataFileReader<GenericData.Record> reader = new DataFileReader<GenericData.Record>(file, datum);
GenericData.Record record = new GenericData.Record(reader.getSchema());
Schema schema = reader.getSchema();
List<String> fieldValues = new ArrayList<>();
JSONArray jsonArray = new JSONArray();
for (Field field : schema.getFields()) {
fieldValues.add(field.name());
}
while (reader.hasNext()) {
reader.next(record);
Map<String, String> jsonFileds = new HashMap<String, String>();
for (String item : fieldValues) {
System.out.println(item);
jsonFileds.put(item, record.get(item).toString());
}
jsonArray.put(jsonFileds);
}
System.out.println(jsonArray.toString());
reader.close();
jsonToCSV(jsonArray);
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void jsonToCSV(JSONArray json) {
File file = new File("avroToJson.csv");
String csv;
try {
csv = CDL.toString(json);
FileUtils.writeStringToFile(file, csv);
} catch (JSONException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
public static void main(String[] args) {
File f = new File("test.avro");
readAvro(f);
}
}

Java error message => is undefined for the type -when creating an object from different package

I have the following code where I am calling a class from another package and I get:
undefined for the type
Package A:
import Excel.WriteExcel;
public void setupAfterSuite() {
WriteExcel x = new WriteExcel();
**x.WriteResults(testresultdata, sheet, workbook);**
Getting the following error:
The method WriteResults(Map, HSSFSheet, HSSFWorkbook)
is undefined for the type WriteExcel
Package B:
public void WriteResults(Map<String, Object[]> testresultdata1, HSSFSheet readsheet1, HSSFWorkbook workbook1) {
// TODO Auto-generated method stub
Set<String> keyset = testresultdata1.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = readsheet1.createRow(rownum++);
Object [] objArr = testresultdata1.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if(obj instanceof Date)
cell.setCellValue((Date)obj);
else if(obj instanceof Boolean)
cell.setCellValue((Boolean)obj);
else if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Double)
cell.setCellValue((Double)obj);
readsheet1.autoSizeColumn(rownum);
for(int i=rownum; i>0; i--){
readsheet1.autoSizeColumn(i);
}
It's probably something minor. Can anyone please advise.
Thanks
You are not sharing some important information, so don't be surprised no-one helped you...
Let me try the same, what you are saying you did.
You didn't share first class name and package name, so I named it ClassA and is defined in q34201803.a package:
package q34201803.a;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import Excel.WriteExcel;
public class ClassA {
public void setupAfterSuite() {
WriteExcel x = new WriteExcel();
HSSFSheet sheet = null;
HSSFWorkbook workbook = null;
Map<String, Object[]> testresultdata;
testresultdata = new LinkedHashMap<String, Object[]>();
x.WriteResults(testresultdata, sheet, workbook);
}
}
Then I created second class based on import in your code:
package Excel;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class WriteExcel {
public void WriteResults(Map<String, Object[]> testresultdata1, HSSFSheet readsheet1, HSSFWorkbook workbook1) {
// not important...
}
}
and it works fine for me.
Please share full source code of your classes I think, there might be problem in imports.
Also you should learn Java naming conventions if you want to code in Java.
Sorry I am new to Coding
**Here is all of the code:**
package Excel;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.Date;
import java.util.Map;
import java.util.Set;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
public class WriteExcel {
public void WriteResults(Map<String, Object[]> testresultdata1, HSSFSheet readsheet1, HSSFWorkbook workbook1) {
// TODO Auto-generated method stub
Set<String> keyset = testresultdata1.keySet();
int rownum = 0;
for (String key : keyset) {
Row row = readsheet1.createRow(rownum++);
Object [] objArr = testresultdata1.get(key);
int cellnum = 0;
for (Object obj : objArr) {
Cell cell = row.createCell(cellnum++);
if(obj instanceof Date)
cell.setCellValue((Date)obj);
else if(obj instanceof Boolean)
cell.setCellValue((Boolean)obj);
else if(obj instanceof String)
cell.setCellValue((String)obj);
else if(obj instanceof Double)
cell.setCellValue((Double)obj);
readsheet1.autoSizeColumn(rownum);
for(int i=rownum; i>0; i--){
readsheet1.autoSizeColumn(i);
}
try {
File dir = new File("Results");
dir.mkdir();
FileOutputStream out =new FileOutputStream(new File("Results/TestResult.xls"));
workbook1.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
}
}
**This is the second Class:**
package test;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.LinkedHashMap;
import java.util.Map;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.testng.ITestContext;
import org.testng.annotations.AfterClass;
import org.testng.annotations.BeforeClass;
import org.testng.annotations.DataProvider;
import org.testng.annotations.Test;
import Excel.WriteExcel;
import jxl.Workbook;
import jxl.read.biff.BiffException;
public class UserSettingTest {
//define an Excel Work Book
HSSFWorkbook workbook;
//define an Excel Work sheet
HSSFSheet sheet;
//define a test result data object
Map<String, Object[]> testresultdata;
//define an Excel Work Book
HSSFWorkbook workbookRead;
//define an Excel Work sheet
HSSFSheet Readsheet;
#BeforeClass(alwaysRun = true)
public void setupBeforeSuite(ITestContext context) {
//create a new work book
workbook = new HSSFWorkbook();
//create a new work sheet
//sheet = workbook.createSheet("Test Result");
testresultdata = new LinkedHashMap<String, Object[]>();
//add test result excel file column header
//write the header in the first row
testresultdata.put("1", new Object[] {"Test Step Id", "Action", "Expected Result","Actual Result"});
}
#DataProvider(name = "DP1")
public Object[][] createData1() throws BiffException, IOException
{
Object[][] retObjArr=getTableArray("data1.xls", "DataPool", "imdbTestData1" );
return (retObjArr);
}
#SuppressWarnings("unused")
private Object[][] getTableArray(String xlFilePath, String SheetName, String tableName) throws BiffException, IOException {
String[][] tabArray=null;
Workbook workbook = Workbook.getWorkbook(new File(xlFilePath));
jxl.Sheet sheet = workbook.getSheet(SheetName);
int startRow,startCol, endRow, endCol,ci,cj;
jxl.Cell tableStart=sheet.findCell(tableName);
startRow=tableStart.getRow();
startCol=tableStart.getColumn();
jxl.Cell tableEnd= sheet.findCell(tableName, startCol+1,startRow+1, 100, 64000, false);
endRow=tableEnd.getRow();
endCol=tableEnd.getColumn();
System.out.println("startRow="+startRow+", endRow="+endRow+", " +
"startCol="+startCol+", endCol="+endCol);
tabArray=new String[endRow-startRow-1][endCol-startCol-1];
ci=0;
for (int i=startRow+1;i<endRow;i++,ci++){
cj=0;
for (int j=startCol+1;j<endCol;j++,cj++){
tabArray[ci][cj]=sheet.getCell(j,i).getContents();
}
}
return(tabArray);
}
int RowNo =3;
int testCase=1;
#Test
public void testDataProviderExample(String movieTitle,
String directorName, String moviePlot, String actorName) throws Exception {
//start
String SRowNo = "" + RowNo;
String StestCase = "TC"+ testCase ;
System.out.println("DirectorName is: "+directorName);
System.out.println("DirectorName is: "+moviePlot);
System.out.println("DirectorName is: "+actorName);
testresultdata.put(SRowNo, new Object[] {StestCase,directorName, "Logged Out","Fail"});
RowNo++;
testCase++;
}
#AfterClass
public void setupAfterSuite() {
WriteExcel x = new WriteExcel();
x.WriteResults(testresultdata, Readsheet, workbook);
try {
File dir = new File("Results");
dir.mkdir();
FileOutputStream out =new FileOutputStream(new File("Results/TestResult.xls"));
workbook.write(out);
out.close();
System.out.println("Excel written successfully..");
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
**When i run i get the following**
[TestNG] Running:
C:\Users\xxxxx\AppData\Local\Temp\testng-eclipse-859939429\testng-customsuite.xml
FAILED CONFIGURATION: #AfterClass setupAfterSuite
java.lang.NullPointerException
at Excel.WriteExcel.WriteResults(WriteExcel.java:26)
at test.UserSettingTest.setupAfterSuite(UserSettingTest.java:127)
at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
at sun.reflect.NativeMethodAccessorImpl.invoke(Unknown Source)
at sun.reflect.DelegatingMethodAccessorImpl.invoke(Unknown Source)
at java.lang.reflect.Method.invoke(Unknown Source)
at org.testng.internal.MethodInvocationHelper.invokeMethod(MethodInvocationHelper.java:85)
at org.testng.internal.Invoker.invokeConfigurationMethod(Invoker.java:510)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:211)
at org.testng.internal.Invoker.invokeConfigurations(Invoker.java:138)
at org.testng.internal.TestMethodWorker.invokeAfterClassMethods(TestMethodWorker.java:220)
at org.testng.internal.TestMethodWorker.run(TestMethodWorker.java:111)
at org.testng.TestRunner.privateRun(TestRunner.java:773)
at org.testng.TestRunner.run(TestRunner.java:623)
at org.testng.SuiteRunner.runTest(SuiteRunner.java:357)
at org.testng.SuiteRunner.runSequentially(SuiteRunner.java:352)
at org.testng.SuiteRunner.privateRun(SuiteRunner.java:310)
at org.testng.SuiteRunner.run(SuiteRunner.java:259)
at org.testng.SuiteRunnerWorker.runSuite(SuiteRunnerWorker.java:52)
at org.testng.SuiteRunnerWorker.run(SuiteRunnerWorker.java:86)
at org.testng.TestNG.runSuitesSequentially(TestNG.java:1185)
at org.testng.TestNG.runSuitesLocally(TestNG.java:1110)
at org.testng.TestNG.run(TestNG.java:1018)
at org.testng.remote.RemoteTestNG.run(RemoteTestNG.java:111)
at org.testng.remote.RemoteTestNG.initAndRun(RemoteTestNG.java:204)
at org.testng.remote.RemoteTestNG.main(RemoteTestNG.java:175)
Line 26 referring to: ===> Row row = readsheet1.createRow(rownum++);
You didn't initialize the Readsheet object. This way, you're passing a null argument to WriteResults method.
x.WriteResults(testresultdata, Readsheet, workbook);
That causes NullPointerException at this line.
Row row = readsheet1.createRow(rownum++);
readsheet1 is null.

Categories

Resources