How to export data from postgresql to excel using java? | Sololearn: Learn to code for FREE!


How to export data from postgresql to excel using java?

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

7/7/2017 2:15:16 AM

Muhammad Badrudin

4 Answers

New Answer


import*; import org.apache.poi.hssf.*; import; import; 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://", "postgres", "password"); stmt = connection.createStatement(); String sql = "select employe_id, firstname, lastname from employe"; ResultSet rs = stmt.executeQuery(sql); while({ 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!


I wonder why do you need to use java to export data to excel when you can simply do copy and paste?


this for my practice. i want to make a report of the data to excel.


thank you intro.