Welcome, Guest. Please login or register.
Did you miss your activation email?
Pages: [1]   Go Down
  Print  
Author Topic: Connect to an Excel Spreadsheet using JDBC in Java  (Read 764 times)
0 Members and 1 Guest are viewing this topic.
G. Ritardo
Member
*
*

Reputation: 0
Offline Offline
Posts: 53
Referrals: 0

Awards
« on: May 13, 2009, 04:44:53 PM »

Code
GeSHi (java):
  1. import java.sql.*;
  2.  
  3. public class ExcelODBC {
  4.  
  5.    public static void main(String[] args) {
  6.  
  7.        try {
  8.            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
  9.            Connection con = DriverManager.getConnection("jdbc:odbc:worcester");
  10.            Statement st = con.createStatement();
  11.            ResultSet rs = st.executeQuery("Select * from [Sheet1$]");
  12.  
  13.            ResultSetMetaData rsmd = rs.getMetaData();
  14.            int numberOfColumns = rsmd.getColumnCount();
  15.  
  16.            while (rs.next()) {
  17.  
  18.                for (int i = 1; i <= numberOfColumns; i++) {
  19.                    if (i > 1)
  20.                        System.out.print(", ");
  21.                    String columnValue = rs.getString(i);
  22.                    System.out.print(columnValue);
  23.                }
  24.                System.out.println("");
  25.            }
  26.  
  27.            st.close();
  28.            con.close();
  29.  
  30.        } catch (Exception ex) {
  31.            System.err.print("Exception: ");
  32.            System.err.println(ex.getMessage());
  33.        }
  34.    }
  35. }
Created by GeSHI 1.0.7.20
This part of the code allows you to query the excel spreadsheet with SQL. This is a simple SQL query to select everything from Sheet1 in the spreadsheet.
Code
GeSHi (java):
  1. ResultSet rs = st.executeQuery("Select * from [Sheet1$]");
Created by GeSHI 1.0.7.20

Logged

Founder of www.Retardation-Foundation.com :: A community for retarded people!? Powered by admin Gaylord Ritardo.
Pages: [1]   Go Up
  Print  
 
Jump to:  

Your Ad Here