I am trying to read a .xls file by JExecel Api. I can read some column data by using cell.getContents() easily. But some column give me mysterious value 1, but column type looks like Date. So i check those column type and Find they are Number Type. So i cast those cell in NumberCell. But output looks still mysterious 1.
Workbook workbook = null;
try {
workbook = Workbook.getWorkbook("StandardReport.xls");
Sheet sheet = workbook.getSheet(0);
Cell[] cellRow = sheet.getColumn(0);
for (int row = 4; row < cellRow.length; row++) {
String id = cellRow[row].getContents().trim();
if (id.isEmpty() == false) {
Cell cell1 = sheet.getCell(1, row);
Cell cell2 = sheet.getCell(2, row);
Cell cell3 = sheet.getCell(3, row);
System.out.println(cell1.getContents()+"");
System.out.println(cell2.getContents()+"");
System.out.println(cell3.getContents()+"");
if (cell3.getType() == CellType.NUMBER) {
NumberCell date=(NumberCell)cell3;
System.out.println(date.getContents()+"");
}
/*if (cell3.getType() == CellType.BOOLEAN) {
System.out.println("2");
}
if (cell3.getType() == CellType.BOOLEAN_FORMULA) {
System.out.println("3");
}
if (cell3.getType() == CellType.DATE_FORMULA) {
System.out.println("4");
}
if (cell3.getType() == CellType.EMPTY) {
System.out.println("5");
}
if (cell3.getType() == CellType.ERROR) {
System.out.println("6");
}
if (cell3.getType() == CellType.FORMULA_ERROR) {
System.out.println("7");
}
if (cell3.getType() == CellType.LABEL) {
System.out.println("8");
}
if (cell3.getType() == CellType.NUMBER) {
System.out.println("9");
}
if (cell3.getType() == CellType.NUMBER_FORMULA) {
System.out.println("11");
}
if (cell3.getType() == CellType.STRING_FORMULA) {
System.out.println("12");
}*/
}
}
} catch (IOException | BiffException ex) {
StaticAccess.showMessageDialog("Failed!!", ex);
}
Here is the file link of StandardReport.xls
Related
This question already has answers here:
What is a NullPointerException, and how do I fix it?
(12 answers)
Closed 9 months ago.
I am working on automating some excel task and when running the program, I stumbled across an error that says this:
Exception in thread "main" java.lang.NullPointerException: Cannot invoke "org.apache.poi.xssf.usermodel.XSSFRow.getCell(int)" because the return value of "org.apache.poi.xssf.usermodel.XSSFSheet.getRow(int)" is null
at com.excel.auto.ExcelAuto.main(ExcelAuto.java:43)
Below is the code that I have typed so far:
public class ExcelAuto {
public static void main(String args[]) throws IOException {
// To get File Path
Scanner scannerFilePath = new Scanner(System.in);
System.out.println("Please Enter File Path: ");
String excelFilePath = scannerFilePath.nextLine();
FileInputStream inputStream = new FileInputStream(excelFilePath);
XSSFWorkbook workbook = new XSSFWorkbook(inputStream);
// To get Sheet Name
Scanner scannerSheet = new Scanner(System.in);
System.out.println("Please Enter Excel Sheet Name: ");
String excelSheetName = scannerSheet.nextLine();
XSSFSheet sheet = workbook.getSheet(excelSheetName);
// To set matching transactions to yellow background
CellStyle stylePerfectTrades = workbook.createCellStyle();
stylePerfectTrades.setFillForegroundColor(IndexedColors.YELLOW.getIndex());
stylePerfectTrades.setFillPattern(FillPatternType.SOLID_FOREGROUND);
DataFormatter df = new DataFormatter();
for (int i = 0; i < sheet.getLastRowNum() + 1; i++) {
Cell cellTitleWPBO = sheet.getRow(i).getCell(9);
Cell cellAmountWPBO = sheet.getRow(i).getCell(10);
Cell cellCheckStatusWPBO = sheet.getRow(i).getCell(6);
for (int j = 0; j < sheet.getLastRowNum() + 1; j++) {
Cell cellDescriptionSaxo = sheet.getRow(j).getCell(2);
Cell cellNetChangeSaxo = sheet.getRow(j).getCell(3);
Cell cellCheckStatusSaxo = sheet.getRow(j).getCell(5);
if (df.formatCellValue(cellCheckStatusSaxo).contains("-")) {
if (df.formatCellValue(cellDescriptionSaxo).contains(df.formatCellValue(cellTitleWPBO))) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals");
break;
}
// Transaction with same title but not same amount.
else {//If cell has a different value as the one in the row below it
System.out.println("Not Equals lah");
}
} else if (df.formatCellValue(cellTitleWPBO).contains("Conversion")) {
if (df.formatCellValue(cellDescriptionSaxo).contains("DEPOSIT")) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals (Conversion Deposit)");
break;
} else {
System.out.println("Not Equals Amount(Conversion)");
}
} else if (df.formatCellValue(cellDescriptionSaxo).contains("WITHDRAWAL")) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals (Conversion Deposit)");
break;
} else {
System.out.println("Not Equals Amount(Conversion)");
}
} else {
System.out.println("Not Equals (Conversion)");
}
} else if (df.formatCellValue(cellTitleWPBO).contains("stamp duty")) {
if (df.formatCellValue(cellDescriptionSaxo).contains("WITHDRAWAL")) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals (stamp duty)");
break;
} else {
System.out.println("Not Equals Amount(stamp duty)");
}
} else {
System.out.println("Not Equals (stamp duty)");
}
} else if (df.formatCellValue(cellTitleWPBO).contains("Dividend")) {
if (df.formatCellValue(cellDescriptionSaxo).contains("Corporate Actions ")) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals (dividend)");
break;
} else {
System.out.println("Not Equals Amount (Dividend)");
}
} else {
System.out.println("Not Equals (Dividend)");
}
} else if (df.formatCellValue(cellTitleWPBO).contains("Withdrawal")) {
if (df.formatCellValue(cellDescriptionSaxo).contains("WITHDRAWAL")) {
if (df.formatCellValue(cellNetChangeSaxo).contains(df.formatCellValue(cellAmountWPBO))) {
cellAmountWPBO.setCellStyle(stylePerfectTrades);
cellDescriptionSaxo.setCellStyle(stylePerfectTrades);
cellNetChangeSaxo.setCellStyle(stylePerfectTrades);
cellTitleWPBO.setCellStyle(stylePerfectTrades);
cellCheckStatusSaxo.setCellValue("Checked");
cellCheckStatusWPBO.setCellValue("Checked");
System.out.println("Equals (Withdrawal)");
break;
} else {
System.out.println("Not Equals Amount (Withdrawal)");
}
} else {
System.out.println("Not Equals (Withdrawal)");
}
}
} else {
System.out.println("Checked");
}
}
FileOutputStream outputStream = new FileOutputStream(excelFilePath);
workbook.write(outputStream);
outputStream.flush();
outputStream.close();
System.out.println("Done");
}
}
}
Change code blocks like this:
Cell cellTitleWPBO = sheet.getRow(i).getCell(9);
Cell cellAmountWPBO = sheet.getRow(i).getCell(10);
Cell cellCheckStatusWPBO = sheet.getRow(i).getCell(6);
to Code like this:
XSSFRow row = sheet.getRow(i);
if (row != null) {
Cell cellTitleWPBO = row.getCell(9);
Cell cellAmountWPBO = row.getCell(10);
Cell cellCheckStatusWPBO = row.getCell(6);
}
Below is the code that I am referring for Data driven with excel in selenium. With this code I am getting exception java.lang.NumberFormatException: For input string: "3.0"
public String[][] getDataFromSheet(String excelfilename,String sheetName) {
String datasets[][] = null;
try {
XSSFSheet sheet = workbook.getSheet(sheetName);
int totalRow = sheet.getLastRowNum() + 1;
int totalCol = sheet.getRow(0).getLastCellNum();
datasets = new String[totalRow - 1][totalCol];
for (int i = 1; i < totalRow; i++) {
XSSFRow rows = sheet.getRow(i);
for (int j = 0; j < totalCol; j++) {
XSSFCell cell = rows.getCell(j);
if (cell.getCellTypeEnum() == CellType.STRING) {
datasets[i - 1][j] = cell.getStringCellValue();
}
else if (cell.getCellTypeEnum() == CellType.NUMERIC) {
String cellText = String.valueOf(cell.getNumericCellValue());
datasets[i - 1][j] = cellText;
} else {
datasets[i - 1][j] = String.valueOf(cell.getBooleanCellValue());
}
}
}
return datasets;
} catch (Exception e) {
return datasets;
}
}
test this code for read excel file and set according to your requirnment.
public class Test {
public static void main(String[] args) {
try {
//Path Of your File Enter here
InputStream ExcelFileToRead = new FileInputStream("/home/chavdaan01/Desktop/Aniruddh.xlsx");
XSSFWorkbook workbook = new XSSFWorkbook(ExcelFileToRead);
XSSFSheet sheet = workbook.getSheetAt(0);
XSSFRow row;
XSSFCell cell;
//int break_down=sheet.getPhysicalNumberOfRows();
Iterator rows = sheet.rowIterator();
int i = 0;
while (rows.hasNext())
{
row=(XSSFRow) rows.next();
Iterator cells = row.cellIterator();
int j = 1;
while (cells.hasNext())
{
cell=(XSSFCell) cells.next();
if (cell.getCellType() == XSSFCell.CELL_TYPE_STRING) {
System.out.println(cell.getStringCellValue());
} else if (cell.getCellType() == XSSFCell.CELL_TYPE_NUMERIC) {
System.out.println(cell.getNumericCellValue());
}else if(cell.getCellType() == XSSFCell.CELL_TYPE_BOOLEAN) {
System.out.println(cell.getBooleanCellValue());
}
}
}
} catch (Exception e) {
}
}
}
I am trying to read in each row that has data in the first cell into an ArrayList of Objects. My problem is that my code doesn't seem to be incrementing my counter past the first row. Am I missing something simple?
Code
try
{
wb = new XSSFWorkbook(new FileInputStream(fileName));
}
catch (FileNotFoundException e)
{
e.printStackTrace();
}
catch (IOException e)
{
e.printStackTrace();
}
XSSFSheet sheet = wb.getSheetAt(2);
ArrayList<Object> obj = new ArrayList<Object>();
int rowIndex = 0;
int cellIndex = 0;
XSSFRow row = sheet.getRow(rowIndex);
Iterator<Cell> rowItr = row.iterator();
while(rowIndex <= sheet.getLastRowNum())
{
if(row.getCell(0) == null)
{
continue;
}
else
{
while(rowItr.hasNext() && rowItr.next() != null)
{
XSSFCell cell = row.getCell(cellIndex);
if(cell == null)
{
continue;
}
else
{
obj.add(row.getCell(cellIndex).toString());
}
cellIndex++;
}
rowIndex++;
cellIndex = 0;
}
System.out.println(obj.toString());
}
rowIndex++;
}
}
Output
[ValuSmart Series 1120 Double Hung]
... I get this output 72 times since there are 72 rows in the sheet
Isolated Loop
ArrayList<Object> obj = new ArrayList<Object>();
int rowCounter = 16;
int x = 0;
while(rowCounter <= 21)
{
XSSFRow row = sheet.getRow(rowCounter);
Iterator<Cell> rowItr = row.iterator();
while(rowItr.hasNext() && rowItr.next() != null)
{
XSSFCell cell = row.getCell(x);
if(cell == null)
{
continue;
}
else
{
obj.add(row.getCell(x).toString());
}
x++;
}
rowCounter++;
x = 0;
}
System.out.println(obj.toString());
You're not select the next row anywhere, and your loops are confusing and switch between index- and iterator-based lookups. Try a simple enhanced for loop:
for (Row row : sheet) {
for (Cell cell : row) {
if (cell != null) {
obj.add(row.getCell(x).toString());
}
}
}
System.out.println(obj.toString());
I am coding a program to format the contents of an excel file. Eclipse is saying that the line Cell cell = cellIterator.next(); is unreachable and I don't understand why. Where did I go wrong?
private String formatExcel(File excel)
{
this.statusLabel.setText("formatting...");
try
{
FileInputStream file = new FileInputStream(excel);
try
{
this.workbook = WorkbookFactory.create(file);
}
catch (InvalidFormatException ex)
{
file.close();
}
int excelType = 0;
if ((this.workbook instanceof HSSFWorkbook)) {
excelType = 1;
}
int sheetNum = 0;
try
{
sheetNum = Integer.parseInt(this.sheetNumber.getText());
}
catch (NumberFormatException e)
{
file.close();
}
if ((sheetNum < 1) || (sheetNum > this.workbook.getNumberOfSheets()))
{
file.close();
return "Please input a valid sheet number.";
}
Sheet sheet = this.workbook.getSheetAt(sheetNum - 1);
sheet.setZoom(17, 20);
Iterator<Row> rowIterator = sheet.iterator();
int startRow = Integer.MAX_VALUE;
Iterator<Cell> cellIterator;
for (; rowIterator.hasNext(); cellIterator.hasNext())
{
Row row = (Row)rowIterator.next();
cellIterator = row.cellIterator();
continue;
Cell cell = (Cell)cellIterator.next(); // <- this line is unreachable
switch (cell.getCellType())
{
case 4:
break;
case 0:
break;
case 1:
if (cell.getStringCellValue().trim().equalsIgnoreCase("Condition Code")) {
startRow = cell.getRowIndex();
}
if ((cell.getRowIndex() > startRow + 1) && (cell.getColumnIndex() > 0) && (cell.getColumnIndex() < 5)) {
if (excelType == 0) {
cell.setCellValue(formatCellXSSF(
cell.getStringCellValue(),
cell.getColumnIndex()));
} else {
cell.setCellValue(formatCellHSSF(
cell.getStringCellValue(),
cell.getColumnIndex()));
}
}
if (!cell.getStringCellValue().trim().equalsIgnoreCase("<<Test Data>>")) {
if (!cell.getStringCellValue().trim().equalsIgnoreCase("<<Screenshots>>")) {
break;
}
}
break;
}
}
sheet.autoSizeColumn(5);
file.close();
FileOutputStream out = new FileOutputStream(excel);
this.workbook.write(out);
out.close();
return "";
}
catch (FileNotFoundException ex)
{
return "Error. File is open. Please close it first.";
}
catch (IOException ex) {}
return "Cannot format file because it is open. Please close it first.";
}
You have an unconditionnal continue in your for loop. Next statements are never executed, no way.
for (; rowIterator.hasNext(); cellIterator.hasNext())
{
Row row = (Row)rowIterator.next();
cellIterator = row.cellIterator();
continue;
Cell cell = (Cell)cellIterator.next();
I am working on the utility which dumps the excel sheet content to the database (postgres 9.2 in my case) , The application is working very smoothly when all the cells are filled but whenever i am trying to run my code on the excel sheet which is having empty cell it is giving me NULL POINTER EXCEPTION . Can any one help me......?
code.... snips ...
public ArrayList fillList(int colIndex, int id, List<Cell> cells,
String path) {
// OrderedMap errorMap=new LinkedMap();
String error = null;
ArrayList<String> errorList = new ArrayList<String>();
// errorList=null;
try {
FileInputStream fileIn = new FileInputStream(path);
POIFSFileSystem fs;
fs = new POIFSFileSystem(fileIn);
HSSFWorkbook filename = new HSSFWorkbook(fs);
Cell number = null;
HSSFSheet sheet = filename.getSheetAt(0);
Row firstRow = sheet.getRow(0);
int flag = 0;
String errorValue = null;
int columnNo = colIndex;
if (columnNo != -1) {
for (Row row : sheet) {
if (row.getRowNum() != 0) {
Cell c = row.getCell(columnNo);
// row.getCell(arg0, arg1)
// cells.add(c);
System.out.println(c.getCellType());
if (c.getCellType() == Cell.CELL_TYPE_STRING &&
(id == 2 || id == 3)) {
cells.add(c);
} else if (c.getCellType() == Cell.CELL_TYPE_NUMERIC
&& id == 1) {
String s = row.getCell(columnNo).toString();
double d = Double.parseDouble(s);
String mob = Double.toString(d);
Cell sc = row.createCell((short) 2);
String text = NumberToTextConverter.toText(c
.getNumericCellValue());
// System.out.println(text);
sc.setCellValue(text);
cells.add(sc);
// Date date=c.getDateCellValue();
} else if (c.getCellType() == Cell.CELL_TYPE_NUMERIC && id == 4) {
String s = row.getCell(columnNo).toString();
double d = HSSFDateUtil.getExcelDate(c
.getDateCellValue());
// String date = Double.toString(d);
Cell sc = row.createCell((short) 2);
String date = new SimpleDateFormat("dd-MM-yyyy")
.format(c.getDateCellValue());
// System.out.println(text);
sc.setCellValue(date);
cells.add(sc);
}
else if (c.getCellType() == Cell.CELL_TYPE_BLANK && id == 1 ) {
String s = row.getCell(columnNo).toString();
Cell sc = row.createCell((short)2);
sc.setCellValue("-");
cells.add(sc);
}
else {
switch (c.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
errorValue = Double.toString(c
.getNumericCellValue());
break;
case Cell.CELL_TYPE_STRING:
errorValue = c.getStringCellValue();
break;
}
errorList.add(c.getRowIndex() + "$" + columnNo
+ "$" + errorValue + "$" + id);
}
/*
* if (c == null || c.getCellType() ==
* Cell.CELL_TYPE_BLANK) { cells.add(c); } else {
*
* cells.add(c);
*
* }
*/
flag = 1;
}// if to skip 1st row
}
} else {
// System.out.println("could not find column " + columnWanted +
// " in first row of " + fileIn.toString());
}
return errorList;
} catch (IOException e) {
e.printStackTrace();
} finally {
}
return errorList;
}
Without knowing how you test for null on the cell, then if it throws a NPE on a certain line you should be about to test for null.
if (c == null)
If this really doesn't work then of course you can always catch the NPE
try {
cellType = c.getCellType();
} catch (NullPointerException e) {
// oops Null
// do something else.
}