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.
Related
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 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 trying to write title and price into excel file. I am creating columns but java game me error 'NULL POINTER EXCEPTION' at line number 48, Please help me what is main reason.But if i write at line no 48 ,sheet1.getRow(0).createCell(0).getStringCellValue('Naqash');Then no Null pointer error is showing.
package codeclasses;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.IOException;
import java.util.List;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
import org.openqa.selenium.By;
import org.openqa.selenium.WebDriver;
import org.openqa.selenium.WebElement;
import org.openqa.selenium.chrome.ChromeDriver;
import org.openqa.selenium.chrome.ChromeOptions;
import org.testng.annotations.Test;
public class ReadExcel {
List<WebElement> title, prices;
#Test
public void test() throws IOException {
System.setProperty("webdriver.chrome.driver", "h:\\chromedriver.exe");
ChromeOptions options = new ChromeOptions();
options.addArguments("disable-infobars");
options.addArguments("--start-maximized");
WebDriver driver = new ChromeDriver(options);
driver.get("https://themeforest.net/search/education?referrer=homepage&utf8=%E2%9C%93");
title = driver.findElements(By.xpath("//h3[#class = 'product-list__heading']/a"));
prices = driver.findElements(By.xpath("//p[#class='product-list__price-desktop']"));
File src = new File("./file/Book1.xlsx");
FileInputStream file = new FileInputStream(src);
XSSFWorkbook wb = new XSSFWorkbook(file);
XSSFSheet sheet1 = wb.getSheetAt(0);
for (int i = 0; i < 30; i++) {
int j = 0;
if(sheet1.getRow(i+1)==null){
(48) sheet1.getRow(i+2).createCell(j).setCellValue("Naqash");
sheet1.getRow(i+2).createCell(j+1).setCellValue("Zafar");
}
else{
System.out.println("Cant find the scene");
}
FileOutputStream fileout = new FileOutputStream(src);
wb.write(fileout);
}
}
}
Try to create the row and cell before you insert data into it. For example:
int rowIndex = 0;
int columnIndex = 0;
Row row = sheet1.createRow(rowIndex);
Cell cell = row.createCell(columnIndex);
cell.setCellValue("Naqash");
You can get row by getRow(index) if you have already created it before
The issue is that you never test if the cell is null!
if (cell == null)
{
System.out.println("Cell is Empty in Column:" + cols);
}
else if (cell.getCellType() == HSSFCell.CELL_TYPE_STRING)
{
//code
}
As a general matter, you should be careful while handling Cell.getCellType() function, since an empty cell could be either null or be a CELL_TYPE_BLANK.
I hope it helped.
I uploaded the excel file in mysql 5.7.The details are uploaded smoothly except time.I dont know how to get time value from excel sheet.
Issue:
**java.lang.IllegalStateException: Cannot get a text value from a numeric cell**
**upload.xlsx**
___________________________
|Punch In | Punch |
----------------------------
|9:00:27 Am |19:45:57 PM |
|__________________________|
If i use the below method
String punchin= row.getCell(0).getStringCellValue();
the error will be occured.
If i use the below method
int punchin = (int) row.getCell(0).getNumericCellValue();
no error occured but the values holds zero.
**insert.java**
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
//import java.sql.Date;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.SQLException;
import java.sql.Time;
import java.text.SimpleDateFormat;
import java.util.Date;
import javax.servlet.ServletException;
import javax.servlet.annotation.MultipartConfig;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.Part;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.xssf.usermodel.XSSFSheet;
import org.apache.poi.xssf.usermodel.XSSFWorkbook;
#WebServlet("/insert1")
#MultipartConfig(maxFileSize = 1216584)
public class insert1 extends HttpServlet {
private static final long serialVersionUID = 1L;
protected void doPost(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
try{
Class.forName("com.mysql.jdbc.Driver");
Connection con = (Connection) DriverManager.getConnection("jdbc:mysql://localhost:3306/rough1","root","root");
con.setAutoCommit(false);
PreparedStatement pstm = null ;
Part filepart=request.getPart("filename");
InputStream inputstream=null;
inputstream=filepart.getInputStream();
XSSFWorkbook wb = new XSSFWorkbook(inputstream);
XSSFSheet sheet = wb.getSheetAt(0);
Row row;
for(int i=1; i<=sheet.getLastRowNum(); i++){
row = sheet.getRow(i);
//String punchin= row.getCell(0).getStringCellValue();
int punchin = (int) row.getCell(0).getNumericCellValue();
System.out.println(":::::::::::::::::::::::::: "+punchin);
// String punchout= row.getCell(1).getStringCellValue();
int punchout =(int)row.getCell(1).getNumericCellValue();
System.out.println(":::::::::::::::::::::::::: "+punchout);
// int duration = (int) row.getCell(5).getNumericCellValue();
String sql = "INSERT INTO log VALUES(null,'"+punchin+"','"+punchout+"')";
pstm = (PreparedStatement) con.prepareStatement(sql);
pstm.execute();
System.out.println("Import rows "+i);
}
con.commit();
pstm.close();
con.close();
inputstream.close();
System.out.println("Success import excel to mysql table");
}catch(ClassNotFoundException e){
System.out.println(e);
}catch(SQLException ex){
System.out.println(ex);
}catch(IOException ioe){
System.out.println(ioe);
}
}
}
Table Desc
I is clearly mentioned that you are facing data type mismatch
Please cast the value you will succeed without errors.
String punchin= String.valueOf(row.getCell(0).getNumericCellValue());
Be Caution about data types with cells.
i have written the following program to get list of tables from postgres database and write them into a xls file. i have included the Apache poi library to write xls file. the program is running with out any error, the is also created but the output is not written into the file the file is just empty. plz help me to write the resultset into the file.
package list;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DatabaseMetaData;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.usermodel.Workbook;
public class List
{
public static void main(String[] args) throws SQLException, FileNotFoundException, IOException
{
Connection con = DriverManager.getConnection( "jdbc:postgresql://localhost:5432/db","user","pass");
DatabaseMetaData md = con.getMetaData();
ResultSet rs = md.getTables(null, "public", "%", null);
try (FileOutputStream fileOut = new FileOutputStream("/home/usr/Desktop/list.xls"))
{
Workbook wb = new HSSFWorkbook();
Sheet sheet1 = wb.createSheet("Table List");
Row row = sheet1.createRow(250);
while (rs.next())
{
row.createCell(0).setCellValue(rs.getString(3));
}
wb.write(fileOut);
fileOut.close();
}
catch(SQLException e)
{
System.out.println( "could not get JDBC connection : " + e );
}
}
}
i have rewritten the code as below and now it works.
int i = 0;
while (rs.next())
{
Row row = sheet1.createRow(i);
row.createCell(0).setCellValue(rs.getString(3));
i++;
}
wb.write(fileOut);