This code tries to iterate over an excel file and load the data to a List<List<String>> but it throws java.lang.NullPointerException at resultList.add(rrow) but it is not clear what is the problem with it:
import org.apache.poi.ss.usermodel.Cell;
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 java.io.FileInputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ReadExcel {
public List<List<String>> resultList;
public List<List<String>> ReadExcelToList(String csvPath) throws IOException {
try {
FileInputStream excelFile = new FileInputStream(csvPath);
Workbook workbook = new XSSFWorkbook(excelFile);
System.out.println(workbook.getSheetName(0));
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
List<String> rrow = new ArrayList<>();
while (cellIterator.hasNext()) {
Cell currentCell = cellIterator.next();
switch (currentCell.getCellType()) {
case Cell.CELL_TYPE_STRING:
rrow.add(currentCell.getStringCellValue());
break;
case Cell.CELL_TYPE_NUMERIC:
rrow.add(String.valueOf(currentCell.getNumericCellValue()));
break;
}
}
resultList.add(rrow);
}
} catch (Exception e) {
e.printStackTrace();
}
return resultList;
}
}
java.lang.NullPointerException
at ReadExcel.readExcelToList(ReadExcel.java:40)
at BasicCSVReader.main(BasicCSVReader.java:35)
Your resultList was never created (it's null). You can fix it by defining it as follows:
public List<List<String>> resultList = new ArrayList<>();
Related
I have added all the jars for apache poi into the module path for this project but anytime I try to use it I get the error
Error occurred during initialization of boot layer
java.lang.module.FindException: Module org.slf4j not found, required by org.apache.poi.poi
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
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;
public class DataTesting {
public static void main(String[] args) throws IOException {
String excelFilePath = "H:\\exceltest\\test1.xlsx";
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = firstSheet.iterator();
while (iterator.hasNext()) {
Row nextRow = iterator.next();
Iterator<Cell> cellIterator = nextRow.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
switch (cell.getCellType()) {
case STRING:
System.out.print(cell.getStringCellValue());
break;
case BOOLEAN:
System.out.print(cell.getBooleanCellValue());
break;
case NUMERIC:
System.out.print(cell.getNumericCellValue());
break;
}
System.out.print(" - ");
}
System.out.println();
}
workbook.close();
inputStream.close();
}
I am using Apache POI API to read Excel file and check the quantity of products available or not. I am successfully reading excel file using below code but I am unable to read the specific cell (Quantity Column) to check weather asked product is available or not
package practice;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.Iterator;
public class ReadingExcel {
private static String brand = "Nike";
private static String shoeName = "Roshe One";
private static String colour = "Black";
private static String size = "9.0";
private static String quantity;
public static void main(String [] args){
try {
FileInputStream excelFile = new FileInputStream(new File("C:\\Users\\admin\\Downloads\\Project\\assets\\Shoe_Store_Storeroom.xlsx"));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
DataFormatter dataFormatter = new DataFormatter();
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
String cellValue = dataFormatter.formatCellValue(cell);
System.out.print(cellValue + "\t\t");
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
this is my excel file
using opencsv 4.1 i do this
import org.apache.commons.lang.StringUtils;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
...
try (InputStream excelFile = new FileInputStream(new File(fileName));
Workbook wb = new XSSFWorkbook(excelFile);) {
for (int numSheet = 0; numSheet < wb.getNumberOfSheets(); numSheet++) {
Sheet xssfSheet = wb.getSheetAt(numSheet);
xssfSheet.forEach(row -> {
Cell cell = row.getCell(0);
if (cell != null) {
if(StringUtils.isNumeric(cell.getStringCellValue())){
// Use here cell.getStringCellValue()
}
}
});
}
}
Use below for loop:
for(int r=sh.getFirstRowNum()+1; r<=sh.getLastRowNum(); r++){ //iterating through all the rows of excel
Row currentRow = sh.getRow(r); //get r'th row
Cell quantityCell = currentRow.getCell(4); //assuming your quantity cell will always be at position 4; if that is not the case check for the header value first
String currentCellValue = quantityCell.getStringCellValue();
if(currentCellValue.equalsIgnoreCase(<value you want to campare with>))
//<do your further actions here>
else
//do your further actions here
}
i am trying to compare the filenames with the xlsx sheet ...if the filename matches with the value of the excel sheet...i want to delete that particular row from the excel sheet....
below is the code what i have tried so far ...
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
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 try2 {
public static void main(String[] args)
throws FileNotFoundException, IOException {
File[] files= new File
("C:\\wamp\\www\\ptry\\sample\\xl").listFiles();
String s = null;
for(File file:files){
s=file.getName();
s=s.replaceAll(".xlsx", "");
}
File xl=new File("C:\\wamp\\www\\ptry\\sample\\xl.xlsx");
FileInputStream f=new FileInputStream(xl);
XSSFWorkbook wb = new XSSFWorkbook (f);
XSSFSheet sheet = wb.getSheetAt(0);
int row=sheet.getLastRowNum()+1;
int colm=sheet.getRow(0).getLastCellNum();
for(int i=0;i<row;i++){
XSSFRow r=sheet.getRow(i);
String m=cellToString(r.getCell(0));
if(s.equals(m)){
System.out.println(m);
}
}
}
public static String cellToString(XSSFCell cell) {
int type;
Object result = null;
type = cell.getCellType();
switch (type) {
case XSSFCell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_BLANK:
result = "";
break;
case XSSFCell.CELL_TYPE_FORMULA:
result = cell.getCellFormula();
}
return result.toString();
}
}
here 's' is the variable to hold filenames and 'm' is the variable to hold excel values
The PROBLEM is:
if i use
if(s.equals(m))
{
System.out.println(m);
}
HOW TO DELETE THE MATCHED ROW FROM THE EXCEL???
Eg)
File names:
a.xlsx
b.xlsx
c.xlsx
excel.xlsx
a
b
d
c
i want to remove a and b from the excel.xlsx
UPDATED:
Based on YASH suggustion i tried the below code
if(s.equals(m)){
System.out.println(m);
sheet.removeRow(r);
}
it removed the first value from excel.xlsx(a)....and shows Exception in thread "main" java.lang.NullPointerException error in the below line
String m=cellToString(r.getCell(0));
i tried with
XSSFRow r = sheet.getRow(i);
if(r==null){
continue;
}
it takes only two values(a,b) from excel.xlsx
After removing the row with RemoveRow(r) shift the remaining rows by 1 as shown below to avoid NullPointer Exception
sheet.RemoveRow(r);
int rowIndex = r.RowNum;
int lastRowNum = sheet.LastRowNum;
if (rowIndex >= 0 && rowIndex < lastRowNum)
{
sheet.ShiftRows(rowIndex + 1, lastRowNum, -1);
}
finally i got the answer
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.JButton;
import org.apache.poi.EncryptedDocumentException;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import org.apache.poi.openxml4j.util.ZipSecureFile;
import org.apache.poi.sl.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
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 try1 {
public static void main(String[] args)
throws FileNotFoundException, IOException {
File[] files=new File("D:\\aa\\a").listFiles();
String s = null;
for(File file:files){
s=file.getName();
s=s.replaceAll(".xlsx", "");
File xl=new File("D:\\aa\\w1.xlsx");
FileInputStream f=new FileInputStream(xl);
XSSFWorkbook wb = new XSSFWorkbook (f);
XSSFSheet sheet = wb.getSheetAt(0);
int row=sheet.getLastRowNum();
int colm=sheet.getRow(0).getLastCellNum();
for(int i=0;i<row;i++){
XSSFRow r = sheet.getRow(i);
if(r==null){
sheet.getRow(i+1);
continue;
}
Cell cell=r.getCell(0);
String m=cellToString(r.getCell(0));
if(s.equals(m)){
System.out.println("s :"+m);
sheet.removeRow(r);
}}
FileOutputStream out=
new FileOutputStream(new File("D:\\aa\\w1.xlsx"));
wb.write(out);
}
}public static String cellToString(XSSFCell cell) {
int type;
Object result = null;
type = cell.getCellType();
switch (type) {
case XSSFCell.CELL_TYPE_STRING:
result = cell.getStringCellValue();
break;
case XSSFCell.CELL_TYPE_BLANK:
result = "";
break;
case XSSFCell.CELL_TYPE_FORMULA:
result = cell.getCellFormula();
}
return result.toString();
}
}
Hi how can i create dynamic objects in a loop to store multiple values in the object. Then access those objects to manipulate.
Is it possible to give dynamic variable names for object creation. Can i give dynamic values of variable on the left hand side of an assignment. Please ask me to edit if the question is not clear, if solution already available please point me out to that.
package poi;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.xssf.usermodel.XSSFRow;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.ArrayList;
import java.util.Iterator;
import java.util.List;
public class ExcelRead_UsingMember {
public static int C, R, i;
public static double ID;
private static final String FILE_READ = "C:/Users/m93162/ApachePOI_Excel_Workspace/MyFirstExcel.xlsx";
//private static final String FILE_WRITE = "C:/Users/m93162/ApachePOI_Excel_Workspace/WriteExcel.xlsx";
public static void main(String[] args) {
List<Member> listOfMembers = new ArrayList<Member>();
try {
FileInputStream excelFile = new FileInputStream(new File(FILE_READ));
Workbook workbook = new XSSFWorkbook(excelFile);
Sheet datatypeSheet = workbook.getSheetAt(0);
Iterator<Row> iterator = datatypeSheet.iterator();
while (iterator.hasNext()) {
Row currentRow = iterator.next();
Iterator<Cell> cellIterator = currentRow.iterator();
int i=0;
while (cellIterator.hasNext()) {
Member [member+i] = new Member();
QUESTION: I want to create dynamic objects here and store the values below dynamically. How to approach this.
Cell currentCell = cellIterator.next();
if (currentCell.getCellTypeEnum() == CellType.STRING) {
System.out.print(currentCell.getStringCellValue() + "--");
} else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {
System.out.print(currentCell.getNumericCellValue() + "--");
}
}
System.out.println();
}
} catch (FileNotFoundException e) {
e.printStackTrace();
} catch (IOException e) {
e.printStackTrace();
}
}
}
You can use map.
DynamicObject
DynamicObject {
prvate Map<String, Object> map = new HashMap();
public void addPropery(String key, Object value) {
map.put(key, value);
}
}
Your code
private void processRow(Row row) {
while (cellIterator.hasNext()) {
dynamicObjects[member+i] = new DynamicObject();
DynamicObject dynamicObject = dynamicObjects[member+i];
Cell currentCell = cellIterator.next();
if (currentCell.getCellTypeEnum() == CellType.STRING) {
System.out.print(currentCell.getStringCellValue() + "--");
dynamicObject.addProperty("stringField", currentCell.getStringCellValue());
} else if (currentCell.getCellTypeEnum() == CellType.NUMERIC) {
System.out.print(currentCell.getNumericCellValue() + "--");
dynamicObject.addProperty("numericField", currentCell.getNumericCellValue());
}
}
}
Then you can traverse keys of the map to get all possible values. You can also store other objects(for example, as nested maps) inside the map as values.
Requirement
i need to open excel file. Then i need to check for the date(12/31/2014). If this exist in the file then i need replace with 11/28/2014. Actually excel file is containing the date. But in my code is never passing this condition if (df.format(DateUtil.getJavaDate(cell.getNumericCellValue())).equals(df.format(asOfDate))) {.
Here is the code:
package excelAsOfDate;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.CreationHelper;
import org.apache.poi.ss.usermodel.DateUtil;
import org.apache.poi.ss.usermodel.IndexedColors;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class ExcelAsOfDate {
public static void main(String[] args) {
try {
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date asOfDate = df.parse("12/31/2014");
Date newAsOfDate = df.parse("11/28/2014");
System.out.println("date as of" + df.format(asOfDate));
File directory = new File("C://Users//kondeti.venkatarao//Documents//Regresion_sheets//test");
File[] files = directory.listFiles();
for (File file : files) {
if (file.getName().toLowerCase().endsWith(".xlsx")) {
FileInputStream fis = new FileInputStream(file.getAbsoluteFile());
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(fis);
int i = 1;
while (i < workbook.getNumberOfSheets()) {
// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(i);
// Iterate through each rows one by one
Iterator<Row> rowIterator = sheet.iterator();
while (rowIterator.hasNext()) {
Row row = rowIterator.next();
// For each row, iterate through all the columns
Iterator<Cell> cellIterator = row.cellIterator();
while (cellIterator.hasNext()) {
Cell cell = cellIterator.next();
// Check the cell type and format accordingly
switch (cell.getCellType()) {
case Cell.CELL_TYPE_NUMERIC:
if (DateUtil.isCellDateFormatted(cell)) {
if (df.format(DateUtil.getJavaDate(cell.getNumericCellValue())).equals(df.format(asOfDate))) {
// System.out.println(df.format(cell.getDateCellValue()));
System.out.println(df.format(DateUtil.getJavaDate(cell.getNumericCellValue())));
CreationHelper createHelper = workbook.getCreationHelper();
CellStyle cellStyle = workbook.createCellStyle();
cellStyle.setFillForegroundColor(IndexedColors.RED.getIndex());
cellStyle.setFillPattern(CellStyle.SOLID_FOREGROUND);
cellStyle.setDataFormat(createHelper.createDataFormat().getFormat("m/d/yy"));
cell.setCellValue(newAsOfDate);
cell.setCellStyle(cellStyle);
}
}
break;
}
}
}
i++;
fis.close();
}
//FileOutputStream fileOut = new FileOutputStream("C://Users//kondeti.venkatarao//Documents//Regresion_sheets//test//final//"+file.getName());
FileOutputStream fileOut = new FileOutputStream(file.getAbsoluteFile());
workbook.write(fileOut);
fileOut.close();
fis.close();
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
}
Logging is a key to find your answers.
As I look into the Cell class, I see there is a method named :
getDateCellCalue()
When we look at the setter of that :
void setCellValue(java.util.Date value)
Converts the supplied date to its equivalent Excel numeric value and sets that into the cell.
So you are not comparing correct.
Mine quick suggestion is :
if (df.format(cell.getDateCellValue()).equals(df.format(asOfDate)))
If this doesn't work, put logging on what the df.format(cell.getDateCellValue() produces as String.
Edit :
Did you also noticed this :
DateFormat df = new SimpleDateFormat("dd/MM/yyyy");
Date asOfDate = df.parse("12/31/2014");
Your second date is MM/dd/yyyy