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<>();
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 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();
}
}
I'am reading excel file and storing few properties like cellstyle,columnwidth,row and column index and storing in Map as follows:
package com;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Skeleton {
public Map<Integer, List<List<Object>>> readSkeleton(File input){
Map<Integer, List<List<Object>>> skeletondata = new TreeMap<Integer, List<List<Object>>>();
try {
FileInputStream in = new FileInputStream(input);
XSSFWorkbook wb = new XSSFWorkbook(in);
int sheetIx = 5; //remove if using above for loop
XSSFSheet st = wb.getSheetAt(sheetIx);
int rowcount = 0;
for (Row row:st){
List<List<Object>> skeletonrow = new ArrayList<List<Object>>();
int cellcount = 0;
for (Cell cell:row){
List<Object> skeletoncell = new ArrayList<Object>();
skeletoncell.add(sheetIx); //for sheet Ix
skeletoncell.add(cell.getRowIndex()); //for rowIx
skeletoncell.add(cell.getColumnIndex()); //for columnIx
CellStyle cs = cell.getCellStyle();
int columnwidth = st.getColumnWidth(cellcount);
skeletoncell.add(cs); // for cell style
skeletoncell.add(columnwidth); //for column width
switch (cell.getCellType()) {
/*case Cell.CELL_TYPE_BLANK:
skeletoncell.add(null);
skeletonrow.add(skeletoncell);
break;
case Cell.CELL_TYPE_BOOLEAN:
break;
case Cell.CELL_TYPE_ERROR:
break;
case Cell.CELL_TYPE_FORMULA:
break; */
case Cell.CELL_TYPE_NUMERIC:
skeletoncell.add(cell.toString());
skeletonrow.add(skeletoncell);
break;
case Cell.CELL_TYPE_STRING:
skeletoncell.add(cell.getStringCellValue());
//skeletoncell.add("Abrakadabra");
skeletonrow.add(skeletoncell);
break;
default:
skeletoncell.add(null);
skeletonrow.add(skeletoncell);
break;
}
System.out.println("skeleton cell size: "+skeletoncell.size());
cellcount++;
}
skeletondata.put(rowcount, skeletonrow);
rowcount++;
}
System.out.println("skeleton data :"+skeletondata);
} catch (FileNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
return skeletondata;
}
}
This returns a map element which contains row number as key and each cell along with its properties as value.
I'am trying to store this data into database (postgres) as follows:
package com;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.Reader;
import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.sql.Statement;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
import java.util.TreeSet;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.CellStyle;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
public class Skeleton {
public void skeletonDataToDatabase(File input){
DAOClass dao = new DAOClass();
Connection con = null;
PreparedStatement pst = null;
con = dao.getConnection();
try{
Skeleton skeleton = new Skeleton();
Map<Integer, List<List<Object>>> skeletondata = new TreeMap<Integer, List<List<Object>>>();
skeletondata = skeleton.readSkeleton(input);
Set<Integer> keys = skeletondata.keySet();
for (Integer key : keys){
List<List<Object>> skeletonrow = new ArrayList<List<Object>>();
skeletonrow = skeletondata.get(key);
for (int r=0;r<skeletonrow.size();r++){
List<Object> skeletoncell = new ArrayList<Object>();
skeletoncell = skeletonrow.get(r);
XSSFWorkbook wb = new XSSFWorkbook();
CellStyle cs1 = (CellStyle) skeletoncell.get(3);
//cs1.cloneStyleFrom((CellStyle) skeletoncell.get(3)); // cell style value
System.out.println("cwll style: "+cs1);
/*Schd_Id integer,
SubSchd_Id integer,
RowIx integer,
ColIx integer,
CellStyle_Value character varying(100),
ColumnWidth integer,
Cell_Value character varying(100)*/
//System.out.println("fifth value: "+skeletoncell.get(5));
if(skeletoncell.get(5)==null){ //check for null cell value (blank)
//System.out.println("after if loop true ");
String query = "insert into Template_Skeleton(Schd_Id,SubSchd_Id,RowIx,ColIx,CellStyle_Value,ColumnWidth) " +
"values(?,?,?,?,?,?);";
pst = con.prepareStatement(query);
pst.setInt(1, 1); //Schd id
pst.setInt(2, (int) skeletoncell.get(0)); //Subschd id
pst.setInt(3, (int) skeletoncell.get(1)); //row Ix
pst.setInt(4, (int) skeletoncell.get(2)); //col ix
pst.setObject(5, cs1); //cellstyle value
pst.setInt(6, (int) skeletoncell.get(4)); //column width
}else{
System.out.println("inside else loop false");
String query = "insert into Template_Skeleton(Schd_Id,SubSchd_Id,RowIx,ColIx,CellStyle_Value,ColumnWidth,Cell_Value) " +
"values(?,?,?,?,?,?,?);";
//System.out.println("after query");
pst = con.prepareStatement(query);
pst.setInt(1, 1); //Schd id
pst.setInt(2, (int) skeletoncell.get(0)); //Subschd id
pst.setInt(3, (int) skeletoncell.get(1)); //row Ix
pst.setInt(4, (int) skeletoncell.get(2)); //col ix
pst.setObject(5, cs1); //cellstyle value
pst.setInt(6, (int) skeletoncell.get(4)); //column width
pst.setString(7, (String) skeletoncell.get(5)); //cell calue
//System.out.println("after 7th value");
}
//System.out.println("before execute");
pst.executeUpdate();
//System.out.println("after execute");
}
System.out.println("inserted row :"+key);
}
}catch (SQLException e){
e.printStackTrace();
}
}
}
While executing it shows the below error:
org.postgresql.util.PSQLException: Can't infer the SQL type to use for an instance of org.apache.poi.xssf.usermodel.XSSFCellStyle. Use setObject() with an explicit Types value to specify the type to use.
at org.postgresql.jdbc2.AbstractJdbc2Statement.setObject(AbstractJdbc2Statement.java:1917)
at org.postgresql.jdbc3g.AbstractJdbc3gStatement.setObject(AbstractJdbc3gStatement.java:36)
at com.tcs.Skeleton.skeletonDataToDatabase(Skeleton.java:157)
at com.tcs.Test.main(Test.java:121)
Note: main method is in test class, connection from DAOclass. I have tried to add cellstyle object as string but I want to store it as such because form database i have to render the style to create a new sheet which follows the stored style.
Thanks in advance.
I would recommend serializing the cell style object and storing the serialized value. I typically use Jackson for serializing/deserializing. The cell data shouldn't be large so serializing to a String should be ok. You can the use a large varchar column or a CLOB column.
I realized, instead of storing style objects which is difficult to render, it is better to store style property values. Ex: isBold--true or false
We can do this for as many properties as we need and store as such in database with same style property column name. While rendering we can use the same values while setting the property value.
I am able to read data from excel sheet. However, when I am trying to enter data value from excel sheet into web application it is throwing error message GetCell is not allowing in the eclipse.
please use below code, it will work.
Java Class:
import java.io.File;
import java.io.FileInputStream;
import java.util.Iterator;
import org.apache.poi.ss.usermodel.Cell;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.testng.annotations.Test;
public class TestAutomation {
#Test(groups = { "test_proxy" })
public void test_proxy() throws Exception {
try {
FileInputStream file = new FileInputStream(
new File("d:\\test.xlsx"));
// Create Workbook instance holding reference to .xlsx file
XSSFWorkbook workbook = new XSSFWorkbook(file);
// Get first/desired sheet from the workbook
XSSFSheet sheet = workbook.getSheetAt(0);
// 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:
System.out.print(cell.getNumericCellValue() + "t");
break;
case Cell.CELL_TYPE_STRING:
System.out.print(cell.getStringCellValue() + "t");
break;
}
}
System.out.println("");
}
file.close();
} catch (Exception e) {
e.printStackTrace();
}
}
}