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);
Related
package poi;
import java.io.*;
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;
class Demo
{
public static void main(String a[]) throws IOException
{
String temp ="C:/santosh_chikne/Selenium Script/test.xlsx";
FileInputStream fs = new FileInputStream(temp);
Workbook wb = Workbook.getWorkbook(fs);
}
}
try as following:
String temp ="C:/santosh_chikne/Selenium Script/test.xlsx";
FileInputStream fs = new FileInputStream(temp);
HSSFWorkbook wb = new HSSFWorkbook(fs);
HSSFSheet sh = wb.getSheet("Sheet1");
Row row = sh.getRow(1);
Cell cell = row.getCell(1);
String valueFromXl = cell.getStringCellValue();
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 am working with Apache POI. I am able to read data from excel, but unable to read image from the excel. How to read image from excel.
Instead of puzzling around let's have a complete example.
import org.apache.poi.ss.usermodel.WorkbookFactory;
import org.apache.poi.ss.usermodel.Workbook;
import org.apache.poi.ss.usermodel.PictureData;
import java.io.InputStream;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;
import java.util.Iterator;
class ReadExcelImages {
public static void main(String[] args) throws Exception{
InputStream inp = new FileInputStream("test.xls");
//InputStream inp = new FileInputStream("test.xlsx");
Workbook workbook = WorkbookFactory.create(inp);
List lst = workbook.getAllPictures();
int i = 1;
for (Iterator it = lst.iterator(); it.hasNext(); ) {
PictureData pict = (PictureData)it.next();
String ext = pict.suggestFileExtension();
byte[] data = pict.getData();
if (ext.equals("png")){
FileOutputStream out = new FileOutputStream("pict" + i++ + ".png");
out.write(data);
out.close();
} else if (ext.equals("jpeg")) {
FileOutputStream out = new FileOutputStream("pict" + i++ + ".jpeg");
out.write(data);
out.close();
}
}
}
}
Works for me with HSSF (*.xls) as well as with XSSF (*.xlsx).
I am reading excel sheet using java apache POI. After reading i want to write on the same row, The ode is reading perfectly but not writing I want to create 6th column in every row in each iteration.... here is the code
/**
* Created by Muhammad Hussain on 26/10/2016.
*/
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
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;
import java.util.Scanner;
/**
* A dirty simple program that reads an Excel file.
* #author www.codejava.net
*
*/
public class ReadExcel {
public static void main(String[] args) throws IOException {
String excelFilePath = "C:\\Users\\Muhammad Hussain\\Desktop\\Data-Collection.xlsx";
FileInputStream inputStream = new FileInputStream(new File(excelFilePath));
Workbook workbook = new XSSFWorkbook(inputStream);
Sheet firstSheet = workbook.getSheetAt(4);
Scanner input =new Scanner(System.in);
for (int rowIndex = 1; rowIndex <= 5; rowIndex++) {
Row row = firstSheet.getRow(rowIndex);
Cell cell = row.getCell(3);
String review = cell.getStringCellValue();
System.out.println(review);
String label =input.next();
row.createCell(6).setCellValue(label);
}
inputStream.close();
inputStream.close();
}
}
You are only reading the file and not writing it. You have to put something like this in the end:
FileOutputStream out = new FileOutputStream(new File("..."));
workbook.write(out);
out.close();
I have an excel sheet from where I am reading excel cel values and importing to DB
Using Apache POI :
if (row.getCell(8) != null) {
setActualDeparture(DateUtil.getJavaDate(row.getCell(8).getNumericCellValue()));
}
The excel sheet has null on Cell 8 , so it should not import anything . but it takes dates like 1899-12-31T00:00:00
What could be the issue ?
The Row.getCell(int cellnum) returns only NULL if there is nothing stored in the file for this cell. It returns the cell if there is something stored in the file for this cell. Even if this is only a NumberFormat for example or any other information for this cell.
But there is a second method Row.getCell(int cellnum, Row.MissingCellPolicy policy) http://poi.apache.org/apidocs/org/apache/poi/ss/usermodel/Row.html#getCell%28int,%20org.apache.poi.ss.usermodel.Row.MissingCellPolicy%29 which can be used in your case.
Example:
There is nothing in A1 but there is a special NumberFormat and not General applied.
import org.apache.poi.xssf.usermodel.*;
import org.apache.poi.ss.usermodel.*;
import org.apache.poi.ss.util.*;
import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
import java.io.FileOutputStream;
import java.io.FileNotFoundException;
import java.io.IOException;
import java.io.FileInputStream;
import java.io.InputStream;
class GetEmtyCellTest {
public static void main(String[] args) {
try {
InputStream inp = new FileInputStream("workbook.xlsx");
Workbook wb = WorkbookFactory.create(inp);
Sheet sheet = wb.getSheetAt(0);
Row row = sheet.getRow(0);
System.out.println(row.getCell(0).getNumericCellValue()); //0.0
System.out.println(row.getCell(0, Row.RETURN_BLANK_AS_NULL)); //null
FileOutputStream fileOut = new FileOutputStream("workbook.xlsx");
wb.write(fileOut);
fileOut.flush();
fileOut.close();
} catch (InvalidFormatException ifex) {
} catch (FileNotFoundException fnfex) {
} catch (IOException ioex) {
}
}
}