How to write fetched values from database to Excel file - java

I need your help in storing the fetched values from a SQL statement to an excel file. I wrote the below code, but I am facing difficulties on how to write the fetched values under the appropriate columns. For example at the beginning, I created 3 headers (ID - Name - Salary). Now, I need to write the fetched values from the SQL statement under each appropriate header, but I do not know how to write them. So kindly assist. The code is:
public void GenerateExcel() {
Connection conn = null;
Statement stmt = null;
FileOutputStream fileOut = new FileOutputStream("C:\\Desktop\\poi-test.xls");
HSSFWorkbook workbook = new HSSFWorkbook();
HSSFSheet worksheet = workbook.createSheet("Employee Details");
HSSFRow row1 = worksheet.createRow((short) 0);
HSSFCell cellA1 = row1.createCell((short) 0);
cellA1.setCellValue("ID");
HSSFCell cellB1 = row1.createCell((short) 1);
cellB1.setCellValue("Name");
HSSFCell cellC1 = row1.createCell((short) 1);
cellC1.setCellValue("Salary");
try{
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
stmt = conn.createStatement();
String sql = "SELECT id, name, amount FROM Employee";
ResultSet rs = stmt.executeQuery(sql);
while(rs.next()){
int id = rs.getInt("id");
int age = rs.getString("name");
String first = rs.getInt("amount");
}
rs.close();
workbook.write(fileOut);
fileOut.flush();
fileOut.close();
}catch(SQLException se){
se.printStackTrace();
}catch(Exception e){
e.printStackTrace();
}finally{
try{
if(stmt!=null)
conn.close();
}catch(SQLException se){
}
try{
if(conn!=null)
conn.close();
}catch(SQLException se){
se.printStackTrace();
}
}
}
}

Actually I can't see where you add data to the workbook ?
I can only see you creating the workbook and adding the first row.
while(rs.next()){
int id = rs.getInt("id");
int age = rs.getString("name");
String first = rs.getInt("amount");
// Adding data here
Row newRow = worksheet.createRow(worksheet.getLastRowNum() + 1);
newRow.createCell(0).setCellValue(id);
newRow.createCell(1).setCellValue(age);
newRow.createCell(2).setCellValue(first);
}

Finally stop wasting time writing apache poi boiler plate. Look at MemPOI's solution:
You can try using MemPOI. Take a look:
File file = new File("C:\\Desktop\\poi-test.xls")
Class.forName("com.mysql.jdbc.Driver");
conn = DriverManager.getConnection(DB_URL, USER, PASS);
PreparedStatement prepStmt = this.connection.prepareStatement("SELECT id, name, amount FROM Employee");
new MempoiBuilder()
.setFile(file)
.addMempoiSheet(new MempoiSheet(prepStmt, "Employee Details"))
.build()
.prepareMempoiReportToFile()
.get();
You can easily add a template or a subfoter. Take a look at the doc

Related

opencsv creating empty csv

I need to convert result set into csv for any database (not just postgres)
Empty csv file is being created when I use opencsv.
Here's the code of doGet method in the servlet:
final String JDBC_DRIVER = "org.postgresql.Driver";
final String DB_URL = "jdbc:postgresql://localhost:5432/postgres";
// Database credentials
final String USER = "postgres";
final String PASS = "12345";
response.setContentType("text/html");
PrintWriter out = response.getWriter();
String title = "Database Result";
String docType =
"<!doctype html public \"-//w3c//dtd html 4.0 " +
"transitional//en\">\n";
out.println(docType +
"<html>\n" +
"<head><title>" + title + "</title></head>\n" +
"<body bgcolor=\"#f0f0f0\">\n" +
"<h1 align=\"center\">" + title + "</h1>\n");
PreparedStatement ps = null;
Connection conn = null;
try {
// Register JDBC driver
Class.forName("org.postgresql.Driver");
// Open a connection
conn = DriverManager.getConnection(DB_URL, USER, PASS);
// Execute SQL query
//stmt = conn.createStatement();
String sql = "SELECT * FROM users";
ps = conn.prepareStatement(sql,
ResultSet.TYPE_SCROLL_SENSITIVE,
ResultSet.CONCUR_UPDATABLE);
ResultSet rs = ps.executeQuery();
/*if(rs.next()){
System.out.println("Name = "+rs.getString("first_name"));
}*/ //prints name so rs is not empty
//rs.first();
CSVWriter writer = new CSVWriter(new FileWriter("Test.csv"));
//even tried with seperator '\t' or ','
writer.writeAll(rs, true);
writer.close();
out.println("</body></html>");
// Clean-up environment
rs.close();
ps.close();
conn.close();
} catch (SQLException se) {
//Handle errors for JDBC
se.printStackTrace();
} catch (Exception e) {
//Handle errors for Class.forName
e.printStackTrace();
} finally {
//finally block used to close resources
try {
if (ps != null)
ps.close();
} catch (SQLException se2) {
}// nothing we can do
try {
if (conn != null)
conn.close();
} catch (SQLException se) {
se.printStackTrace();
}//end finally try
} //end try
Not sure what's the error. Tried different way but csv is always empty.
Even tried writer.flush(), rs.beforeFirst(), rs.first() nothing works.
Is your problem that you do not see data in the html - if that is the case then instead of creating a new FileWriter in the CSVWriter just pass in you out variable.
Or is it that you checked the Test.csv and file and nothing is there? if so then first check to see if there is actually data in the result set by adding the following after executeQuery:
rs.last();
long numberOfRecords = rs.getRow();
rs.beforeFirst();
System.out.println("Number of Users in table is: " + numberOfRecords);

Getting blob image in mysql using restful web service

I've done listing the strings like the name etc. but I've got problem in retrieving the image. Here's my code of retrieving it. It is in the arraylist. I don't know if i'm getting the right output. Please help me. Here's my code
public ArrayList<Objects> getTaxiDetails(Connection con, String taxi_plate_no) throws SQLException{
ArrayList<Objects> taxiDetailsList = new ArrayList<Objects>();
PreparedStatement stmt = con.prepareStatement("SELECT * from taxi_driver where taxi_plate_no = '" +taxi_plate_no+ "'");
//PreparedStatement stmt = con.prepareStatement("SELECT * from taxi_driver");
ResultSet rs = stmt.executeQuery();
try{
byte[] bytes = null;
while(rs.next()){
Objects taxiObjects = new Objects();
taxiObjects.setDriver_contact_no(rs.getString("driver_contact_no"));
taxiObjects.setDriver_name(rs.getString("driver_name"));
taxiObjects.setTaxi_plate_no(rs.getString("taxi_plate_no"));
taxiObjects.setDriver_operator(rs.getString("driver_operator"));
taxiObjects.setDriver_operator_address(rs.getString("driver_operator_address"));
taxiObjects.setImage(rs.getBytes("image"));
Blob image = rs.getBlob(1);
byte[] allBytesInBlob = image.getBytes(1, (int) image.length());
taxiDetailsList.add(taxiObjects);
}
} catch (SQLException e){
e.printStackTrace();
} return taxiDetailsList;
}
Here's the output

Issue with getBinaryStream(index)

I am getting null value when I am reading the blob data from database. What might be the issue? Can some one help me on this?
Connection con = null;
PreparedStatement psStmt = null;
ResultSet rs = null;
try {
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
} catch (ClassNotFoundException e) {
e.printStackTrace();
}
con =
DriverManager.getConnection("jdbc:oracle:thin:#MyDatabase:1535:XE","password","password");
System.out.println("connection established"+con);
psStmt = con
.prepareStatement("Select Photo from Person where Firstname=?");
int i = 1;
psStmt.setLong(1, "Nani");
rs = null;
rs = psStmt.executeQuery();
InputStream inputStream = null;
while (rs.next()) {
inputStream = rs.getBinaryStream(1);
//Blob blob = rs.getBlob(1);
//Blob blob1 = (Blob)rs.getObject(1);
//System.out.println("blob length "+blob1);//rs.getString(1);
}
System.out.println("bytessssssss "+inputStream);//here i am getting null value.
} catch (SQLException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
I believe you didn't use setString function to assign any value to firstname which leads to null
for example:
ps.preparedStatement("Select photo from person where firstname = ?");
ps.setString(1,"kick"); <----- add this line
system.out.println("bytes "+rs.getBinaryStream(1));
Another suggestions
there is no need to use rs = null; inside try catch block because you have rs=null; at beginning of
your code.
change
InputStream inputStream = null;
to
InputStream inputStream = new InputStream();
or
get rid of InputStream inputStream = null;
source you should take a look at
The most obvious error is using setLong instead of setString.
However one practice is fatal: declaring in advance. This in other languages is a good practice, but in java one should declare as close as possible.
This reduces scope, by which you would have found the error! Namely inputStream is called after a failed rs.next() - outside the loop. Maybe because no records were found.
This practice, declaring as near as feasible, also helps with try-with-resources which were used here to automatically close the statement and result set.
Connection con = null;
try {
Class.forName("oracle.jdbc.driver.OracleDriver");
con = DriverManager.getConnection(
"jdbc:oracle:thin:#MyDatabase:1535:XE","password","password");
System.out.println("connection established"+con);
try (PreparedStatement psStmt = con.prepareStatement(
"Select Photo from Person where Firstname=?")) {
int i = 1;
psStmt.setString(1, "Nani");
try (ResultSet rs = psStmt.executeQuery()) {
while (rs.next()) {
try (InputStream inputStream = rs.getBinaryStream(1)) {
//Blob blob = rs.getBlob(1);
//Blob blob1 = (Blob)rs.getObject(1);
//System.out.println("blob length "+blob1);//rs.getString(1);
Files.copy(inputStream, Paths.get("C:/photo-" + i + ".jpg"));
}
++i;
}
//ERROR System.out.println("bytessssssss "+inputStream);
} // Closes rs.
} // Closes psStmt.
}
1- In your code when setting the parameter's value of SQL query, be sure to use the appropriate data type of the field. So here you should use
psStmt.setString(1, "Nani");
instead of
psStmt.setLong(1, "Nani");
2- Make sure that the query is correct (Table name, field name).
3- Make sure that the table is containing data.

performance decreses after 45k record, when rewriting excel (.xlsm) file from java resultset

This code works perfectly for records below 35k and write data on Sheet but if record exist 45k performance slow down and dead without any exception or error,
and doesn't create any file.
how can i overcome this issue?
public void dbConnect(String driver_connect_string, String db_connect_string, String db_userid, String db_password){
try{
//database connectivity
Statement statement = conn.createStatement();
String queryString = propq.getProperty("Query");
ResultSet rs = statement.executeQuery(queryString);
OPCPackage pkg = OPCPackage.open(new File(("sourceFile")));
XSSFWorkbook wb_template;
wb_template = new XSSFWorkbook(pkg);
System.out.println("package loaded");
Sheet sheet = wb_template.getSheetAt(0);
Row row = null;
int index = 1;
while (rs.next()) {
try{
row = sheet.createRow(index);
row.createCell(0).setCellValue(rs.getString(1));
row.createCell(1).setCellValue(rs.getString(2));
row.createCell(2).setCellValue(rs.getString(3));
.
.
row.createCell(23).setCellValue(rs.getString(25));
System.out.println(index);
}
catch(Exception e){
System.out.println(e);
}
index++;
}
FileOutputStream out = new FileOutputStream(new File(("destFile")));
wb_template.write(out);
out.flush();
out.close();
}catch(Exception e){
e.printStackTrace();
}
}

generating excel sheet from database

I am trying to create excel sheet with different different values from different table in database by using some joins my code is working but record is getting printed twice in the excel sheet i do not know i have checked everything please anyone help me here...
here is my code..
public class ExcelFileGen extends HttpServlet {
public void doGet(HttpServletRequest request, HttpServletResponse response)
throws ServletException, java.io.IOException {
HttpSession session = request.getSession(true);
String eid = (String) session.getAttribute("eid");
try {
String filename = "D:\\DailyWork.xls";
HSSFWorkbook hwb = new HSSFWorkbook();
HSSFSheet sheet = hwb.createSheet("new sheet");
HSSFRow rowhead = sheet.createRow((short) 0);
rowhead.createCell(0).setCellValue("date");
rowhead.createCell(1).setCellValue("description");
rowhead.createCell(2).setCellValue("Support HRS");
rowhead.createCell(3).setCellValue("Development HRS");
rowhead.createCell(4).setCellValue("training HRS");
rowhead.createCell(5).setCellValue("Research HRS");
rowhead.createCell(6).setCellValue("Meeting HRS");
rowhead.createCell(7).setCellValue("leave hrs");
rowhead.createCell(8).setCellValue("Project Name");
rowhead.createCell(9).setCellValue("activity");
rowhead.createCell(10).setCellValue("eid");
rowhead.createCell(11).setCellValue("intime");
rowhead.createCell(12).setCellValue("outtime");
Connection con = ConnectionManager.getConnection();
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("select u.date, u.description, u.field1, u.field2, u.field3, u.field4, u.field5, u.field6, u.field7, u.activity, u.eid, d.intime, d.outtime, d.eid from updatework AS u, fulltime as d where d.eid = u.eid AND u.eid='"
+ eid + "'");
int i = 1;
while (rs.next())
{
HSSFRow row = sheet.createRow((short) i);
row.createCell(0).setCellValue(rs.getString("date"));
row.createCell(1).setCellValue(rs.getString("description"));
sheet.autoSizeColumn(1);
row.createCell(2).setCellValue(rs.getString("field1"));
sheet.autoSizeColumn(2);
row.createCell(3).setCellValue(rs.getString("field2"));
sheet.autoSizeColumn(3);
row.createCell(4).setCellValue(rs.getString("field3"));
sheet.autoSizeColumn(4);
row.createCell(5).setCellValue(rs.getString("field4"));
sheet.autoSizeColumn(5);
row.createCell(6).setCellValue(rs.getString("field5"));
sheet.autoSizeColumn(6);
row.createCell(7).setCellValue(rs.getString("field6"));
sheet.autoSizeColumn(7);
row.createCell(8).setCellValue(rs.getString("field7"));
sheet.autoSizeColumn(8);
row.createCell(9).setCellValue(rs.getString("activity"));
sheet.autoSizeColumn(9);
row.createCell(10).setCellValue(rs.getString("eid"));
sheet.autoSizeColumn(10);
row.createCell(11).setCellValue(rs.getString("intime"));
sheet.autoSizeColumn(11);
row.createCell(12).setCellValue(rs.getString("outtime"));
sheet.autoSizeColumn(12);
i++;
}
FileOutputStream fileOut = new FileOutputStream(filename);
hwb.write(fileOut);
fileOut.close();
System.out.println("Your excel file has been generated!");
} catch (Exception ex) {
System.out.println(ex);
}
}
}
here is my solution everything was correct only but query was not proper now query is correct and its working ...
ResultSet rs = st.executeQuery("select u.date, u.description, u.field1, u.field2, u.field3, u.field4, u.field5, u.field6, u.field7, u.activity, u.eid, d.intime, d.outtime, d.eid from updatework AS u, fulltime as d where (d.date=u.date) and (d.eid = u.eid) AND u.eid='"
+ eid + "'");

Categories

Resources