First of all, I apologize for my bad english, it's not my primary language.
I'm having a problem with my code when it's reading an excel file (xlsx). The first time I used my code it works perfectly, but now I can't use it.
The excel content is printed on the console, but next to it there is a NullPointerException that is caused by the for loop marked with the (-->>>).
If anyone can help me, I would be very thankful, this code has given me several headaches.
package modleerjava;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class leerExcel {
public void readExcel(String rutaFile,String nombreFile, String sheetName )
throws IOException {
File file = new File ("C:/Users/Pablo/Desktop/prueba.xlsx");
FileInputStream inputStream = new FileInputStream(file);
XSSFWorkbook excelWorkbook ;
excelWorkbook = new XSSFWorkbook(inputStream);
Sheet excelSheet = excelWorkbook.getSheet(sheetName);
int filasCount = excelSheet.getLastRowNum()-excelSheet.getFirstRowNum();
for (int i=0; i< filasCount+1 ; i++) {
Row filas;
filas = excelSheet.getRow(i);
-->>> for (int j=0 ; j < filas.getLastCellNum(); j++) {
System.out.print(filas.getCell(j).getStringCellValue()+"|| ");
}
System.out.println();
}
}
}
Your sheet probably has missing rows or cells. The best way to iterate over a spreadsheet in poi is using the for each syntax like this.
package modleerjava;
import java.io.File;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
public class leerExcel {
public void readExcel(String rutaFile,String nombreFile, String sheetName )
throws IOException {
Workbook wb = WorkbookFactory.create(new File("C:/Users/Pablo/Desktop/prueba.xlsx"));
Sheet excelSheet = wb.getSheet(sheetName);
for (Row filas: excelSheet) {
for (Cell cell: filas) {
System.out.print(cell.getStringCellValue()+"|| ");
}
System.out.println();
}
}
}
Many simple questions can be answered by looking at the quick guide on the poi website.
By seeing the code, I think that NullPointerException will occur if the first row in the excel sheet is blank. So, I have created an Iterator on rows.
Try the below code:
package modleerjava;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class leerExcel {
public void readExcel(String rutaFile,String nombreFile, String sheetName )
throws IOException {
File file = new File ("C:/Users/Pablo/Desktop/prueba.xlsx");
FileInputStream inputStream = new FileInputStream(file);
XSSFWorkbook excelWorkbook ;
excelWorkbook = new XSSFWorkbook(inputStream);
inputStream.close();
Sheet excelSheet = excelWorkbook.getSheet(sheetName);
//int filasCount = excelSheet.getLastRowNum()-excelSheet.getFirstRowNum();
Iterator<Row> row = excelSheet.rowIterator();
while(row.hasNext()) {
Row filas;
filas = row.next();
for (int j=0 ; j < filas.getLastCellNum(); j++) {
System.out.print(filas.getCell(j).getStringCellValue()+"|| ");
}
System.out.println();
}
}
}
Related
Trying to use payload variable extracted from an excel sheet in another executable class where I want to post the payload on MQ, although not able to access the variable. How can I use this variable to other class.
package datasource;
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;
import java.io.FileInputStream;
import java.io.IOException;
public class excelUtility {
public static void main(String[] args) throws IOException {
String excelfilePath= "src/main/resources/Book1.xlsx";
FileInputStream inputStream= new FileInputStream(excelfilePath);
XSSFWorkbook workbook=new XSSFWorkbook(inputStream);
XSSFSheet sheet= workbook.getSheet("sheet1");
int rows= sheet.getLastRowNum();
int cols= sheet.getRow(1).getLastCellNum();
for (int r=0; r<=rows; r++){
XSSFRow row= sheet.getRow(r);
for(int c=0; c<cols; c++){
XSSFCell cell= row.getCell(1);
String payload= cell.getStringCellValue();
System.out.println(payload);
}
}
}
}
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
import com.itko.lisa.vse.stateful.model.TransientResponse;
import com.itko.lisa.vse.stateful.model.Response;
import com.itko.util.ParameterList;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.Iterator;
import java.lang.String;
import org.apache.log4j.*;
import groovy.util.logging.*;
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;
FileInputStream fileInputStream = new FileInputStream("C:/Softwares/LISA/CBO_CurrentBalance1/Data/BalanceReport.xlsx");
//FileInputStream fileInputStream = new FileInputStream("/home/lisa-user/Data/CBOPayment.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(fileInputStream)
XSSFSheet sheet = workbook.getSheet("Sheet1");
XSSFRow row;
XSSFCell cell;
Iterator rows = sheet.rowIterator();
while (rows.hasNext()) {
row = (XSSFRow) rows.next();
Iterator cells = row.cellIterator();
AccountNumber1 = testExec.getStateObject("AccountNumber1")
AccountNumber2 = testExec.getStateObject("AccountNumber2")
if (AccountNumber1 == cells.next().getStringCellValue()) {
if(cells.hasNext()) {
Balance = cells.next().getNumericCellValue();
testExec.setStateValue("Balance1", Balance);
}
}
if (AccountNumber2 == cells.next().getStringCellValue()) {
if (cells.hasNext()) {
Balance = cells.next().getNumericCellValue();
testExec.setStateValue("Balance2", Balance);
}
}
}
you need something like this :
don't get confused with the naming convention as this is one of my code.
the problem is
DataFormatter fmt = new DataFormatter();
String _charges = fmt.formatCellValue(sheet.getRow(45).getCell(CellReference.convertColStringToIndex("D")));
what you are doing is trying to fetch a numeric value from the sheet whereas it is saved as a String so you need to convert it to String before you can use it. The code i have pasted is not the exact solution but i hope you might get the hint about the solution.
I have created a project with seperate source folder for each module, say mod1 & mod2 and the src source folder as common for each source folder.
And I created DataProvider_Repository.java file for reading data from excel sheet. Which now I need to put Data Provider in each source folder for accessing it in each testcase(Eg:Registration.java or Del.java).
How can I make it common & put in src folder.
DataProvider_Repository.java contains same code for reading data from excel sheet.
DataProvider_Repository.java
package online;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.lang.reflect.Method;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.DataProvider;
public class DataProvider_Repository {
#DataProvider(name="dataProviderRepo")
public static Object[][] getDataFromDataprovider(Method m) throws IOException{
Object[][] object = null;
String filePath = System.getProperty("user.dir")+"\\";
String fileName = "sample.xlsx";
String sheetName= "sampleSheet";
File file = new File(filePath+"\\"+fileName);
FileInputStream inputStream = new FileInputStream(file);
Workbook wb = new XSSFWorkbook(inputStream);
Sheet s = wb.getSheet(sheetName);
//Find number of rows in excel file
int rowCount = s.getLastRowNum()-s.getFirstRowNum();
object = new Object[rowCount][6];
for (int i = 0; i < rowCount; i++) {
//Loop over all the rows
Row row = s.getRow(i+1);
int lst = row.getLastCellNum();
//Create a loop to print cell values in a row
for (int j = 0; j < lst; j++) {
//Print excel data in console
if(row.getCell(j) != null){
object[i][j] = row.getCell(j).toString();
}
}
object[i][lst-1] = Integer.toString(i);
}
return object;
}
}
Registration.java
package online;
import org.testng.annotations.Test;
public class Registration {
#Test(dataProviderClass=DataProvider_Repository.class,dataProvider="dataProviderRepo")
public void OnlineRegs(String testcaseName,String keyword,String objectName,String objectType,String value, String rowNum) throws Exception {
System.out.println("=======OnlineReg===========");
//Operations here...
}
}
The folder structure is
I have an excel file with DDE links to external sources. I am trying to read those values into my java application.
I am using Apache POI library to read the excel. When trying, I get the following error:
Exception in thread "main" java.lang.IllegalStateException: Cannot get a numeric value from a text cell
at org.apache.poi.hssf.usermodel.HSSFCell.typeMismatch(HSSFCell.java:643)
at org.apache.poi.hssf.usermodel.HSSFCell.getNumericCellValue(HSSFCell.java:668)
at BasketExcelRead.run(BasketExcelRead.java:40)
at Tester.main(Tester.java:7)
My code is
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.List;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
public class BasketExcelRead implements Runnable {
public void run() {
String inputFile = "someexcel.xls";
List<String> code = new ArrayList<String>();
List<Double> bid = new ArrayList<Double>();
List<Double> share = new ArrayList<Double>();
try {
FileInputStream file = new FileInputStream(new File(inputFile));
HSSFWorkbook workbook = new HSSFWorkbook(file);
HSSFSheet sheet = workbook.getSheetAt(0);
int ss = sheet.getPhysicalNumberOfRows();
for (int i = 0; i < ss; i++) {
HSSFRow row = sheet.getRow(i);
HSSFCell cellCode = row.getCell(0);
HSSFCell cellBid = row.getCell(7);
HSSFCell cellShare = row.getCell(9);
code.add(cellCode.getStringCellValue());
bid.add(cellBid.getNumericCellValue());
share.add(cellShare.getNumericCellValue());
}
} catch (IOException e) {
e.printStackTrace();
} finally {
System.out.println("done reading");
}
for (int i = 0; i < 30; i++) {
System.out.println(code.get(i)+" "+bid.get(i)+" "+share.get(i));
}
}
}
The cell that text/numeric value conflict happens at bid.add(cellBid.getNumericCellValue());
This cellBid is the DDE link within the excel file which shows some numeric values