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.
Related
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 trying to use the JasperReports library in a plain Java application. It won't compile because it can't find the aegean chart theme. Can someone point me to a simple example of how to get a .jrxml file to compile and pass this theme to the JasperCompileManager?
package com.asset.jasper.mvc.reports;
import java.io.File;
import java.io.IOException;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.SQLException;
import java.util.HashMap;
import java.util.Map;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import java.sql.PreparedStatement;
import net.sf.jasperreports.engine.JRDataSource;
import net.sf.jasperreports.engine.JRException;
import net.sf.jasperreports.engine.JRResultSetDataSource;
import net.sf.jasperreports.engine.JasperCompileManager;
import net.sf.jasperreports.engine.JasperExportManager;
import net.sf.jasperreports.engine.JasperFillManager;
import net.sf.jasperreports.engine.JasperPrint;
import net.sf.jasperreports.engine.JasperReport;
import net.sf.jasperreports.chartthemes.simple.AegeanSettingsFactory;
import net.sf.jasperreports.chartthemes.simple.XmlChartTheme;
import net.sf.jasperreports.chartthemes.spring.AegeanChartTheme;
public class AssetReport {
private static final Log log = LogFactory.getLog (AssetReport.class);
public static void main(String[] args) throws JRException, IOException {
AegeanChartTheme aegeanChartTheme = new AegeanChartTheme();
XmlChartTheme.saveSettings(
AegeanSettingsFactory.createChartThemeSettings(),
new File("src/net/sf/jasperreports/chartthemes/simple/aegean.jrctx")
);
JasperReport jasperReport = JasperCompileManager.compileReport(
"/resources/ARKREPORT.jrxml");
Map<String, Object> parameters = new HashMap<String, Object>();
Connection myconnection = getConnection();
String jdbcString = "select * from asset";
PreparedStatement statement = null;
try {
statement = myconnection.prepareStatement(jdbcString.toString());
} catch (SQLException e) {
e.printStackTrace();
}
ResultSet rs = null;
try {
rs = statement.executeQuery();
} catch (SQLException e) {
e.printStackTrace();
}
JRDataSource dataSource = new JRResultSetDataSource(rs);
JasperPrint jasperPrint = JasperFillManager.fillReport(jasperReport, parameters, dataSource);
File outDir = new File("/Users/denisputnam/tmp");
outDir.mkdirs();
JasperExportManager.exportReportToPdfFile(jasperPrint, "/tmp/StyledTextReport.pdf");
JasperExportManager.exportReportToHtmlFile(jasperPrint, "/tmp/StyledTextReport.html");
}
static public Connection getConnection() {
Connection connection = null;
try {
connection = DriverManager.getConnection("jdbc:mysql://localhost:3306/assetcore", "assetcore", "password");
} catch (SQLException e) {
e.printStackTrace();
}
return connection;
}
}
This is my servlet, I successfully read the data from database and displayed it in the browser but I want to display this data in json format can any one tell me
package com.file;
import java.io.IOException;
import java.io.PrintWriter;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.ResultSet;
import java.sql.Statement;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
public class GetDataTable extends HttpServlet{
public void doGet(HttpServletRequest req, HttpServletResponse res)
throws ServletException, IOException
{
res.setContentType("application/json");
PrintWriter pw = res.getWriter();
Connection con;
Statement stmt;
ResultSet rs;
try{
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection("jdbc:oracle:thin:#localhost:java","java","java");
stmt = con.createStatement();
rs = stmt.executeQuery("Select * from SERIESCHART");
pw.println("DATA "+ "VALUE" + "<br>");
while(rs.next())
{
pw.println(rs.getString(1)+" "+rs.getString(2) + "<br>");
}
}
catch (Exception e){
pw.println(e);
}
}
}
You can use json-simple
sample code
import org.json.simple.JSONObject;
JSONObject obj = new JSONObject();
obj.put("name", "foo");
obj.put("num",rs.getInt(1));
obj.put("balance", rs.getString(2));
obj.put("is_vip", rs.getString(3));
System.out.print(obj);
You can do something like this:
...
JsonWriter writer = new JsonWriter(new OutputStreamWriter(res.getOutputStream(), "UTF-8"));
writer.beginArray();
while(rs.next())
{
writer.beginObject();
writer.name("DATA").value(rs.getString(1));
writer.name("VALUE").value(rs.getString(2));
writer.endObject();
}
writer.endArray();
writer.close();
....
This will fetch your results from db and put the json representation into responce outputstream
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);