How to export data from postgresql to excel using java? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
0

How to export data from postgresql to excel using java?

can you give me a simple code with a simple table. thank you.

7th Jul 2017, 2:15 AM
Muhammad Badrudin
Muhammad Badrudin - avatar
4 Answers
0
import java.io.*; import org.apache.poi.hssf.*; import org.apache.poi.ss.usermodel.Cell; import java.io.FileOutputStream; import java.sql.*; public class ReadPostgresandExcel{ static String [] array = new String[3]; public static void main(String[] args){ readPostgres(); writeExcelData(); } public static void writeExcelData(){ //create blank workbook HSSFWorkbook workbook = new HSSFWorkbook(); HSSFSheet spreadsheet = workbook.createSheet("Sheet1"); try{ HSSFRow row = spreadsheet.createRow(0); Cell cell = row.createCell(0); String result = array[0] + " " + array[1] + " " + array[2]; cell.setCellValue(result); FileOutputStream out = new FileOutputStream(new File("C:\\Users\\XXX\\Documents\\CreateWorkbook.xls")); workbook.write(out); out.close(); }catch(Exception e){ System.out.println("Error: " + e); } System.out.println("createworkbook.xls created!"); } public static void readPostgres(){ try{ Class.forName("org.postgresql.Driver"); }catch(ClassNotFoundException e){ System.out.println("Where psql JDBC jar?" + "include library path!"); e.printStackTrace(); return; } System.out.println("psql driver success!"); Connection connection = null; Statement stmt = null; try{ connection = DriverManager.getConnection("jdbc:postgresql://127.0.0.1:5432/postgres", "postgres", "password"); stmt = connection.createStatement(); String sql = "select employe_id, firstname, lastname from employe"; ResultSet rs = stmt.executeQuery(sql); while(rs.next()){ int id = rs.getInt("employe_id"); String first = rs.getString("firstname"); String last = rs.getString("lastname"); array[0] = "" + id; array[1] = first; array[2] = last; } }catch(SQLException e){ println(""); } if(connection != null){ println("db Success!"); }else{ println("Failed sql connection!"); } } } // I shorted a little with import, println... // Sorry for typos!
8th Jul 2017, 6:46 PM
intro
+ 9
I wonder why do you need to use java to export data to excel when you can simply do copy and paste?
7th Jul 2017, 3:04 AM
CC Calvello
CC Calvello - avatar
0
this for my practice. i want to make a report of the data to excel.
7th Jul 2017, 4:22 AM
Muhammad Badrudin
Muhammad Badrudin - avatar
0
thank you intro.
9th Jul 2017, 12:07 AM
Muhammad Badrudin
Muhammad Badrudin - avatar