Create excel from JDBC resultset

Here is some simple code to transform a JDBC resulset to an excel-sheet.
You can also use a tool like Apache POI, but this one is easy and simple.

package com.javaoracleblog.servlets;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.OutputStreamWriter;
import java.io.PrintWriter; import java.sql.Connection; import java.sql.DriverManager;
import java.sql.ResultSet; import java.sql.ResultSetMetaData;
import java.sql.SQLException;
import java.sql.Statement;
import java.sql.Types;
import java.math.BigDecimal;
public class ExcelWriter {
 protected String excelXmlHeader() {   return ("/n”>http://www.w3.org/TR/REC-html40”>n”     + “    n”     + ” n”     + “n”     + ” n”     + ”
“);
  for (int j = 0; j < columnNames.length; j++) {    result.append("
” + columnNames[j] + “

“);

 }
 public static void main(String[] args) {   try {    String driverName = "oracle.jdbc.driver.OracleDriver";    Class.forName(driverName);
   Connection conn;    String url = "jdbc:oracle:thin:@orakt02:1521:aridev01";    conn = DriverManager.getConnection(url, "ari", "ari");    Statement stmt = conn.createStatement();    ResultSet rs = stmt.executeQuery("SELECT * FROM ari_config");
   PrintWriter out;    try {     out = new PrintWriter(new OutputStreamWriter(       new FileOutputStream("c:/test.xls")));     ExcelWriter ew = new ExcelWriter();     ew.writeResultset(out, rs);     out.close();
   } catch (FileNotFoundException e) {     // TODO Auto-generated catch block     e.printStackTrace();    }
  } catch (SQLException e) {    // TODO Auto-generated catch block    e.printStackTrace();   } catch (ClassNotFoundException e) {    // TODO Auto-generated catch block    e.printStackTrace();   }
 }
}

One thought on “Create excel from JDBC resultset”

Leave a Reply

Your email address will not be published. Required fields are marked *