Leggere i dati da un foglio Excel in Java

Java e Excel… mah…

Prendete il foglio Excel, compilate una tabella ed assegnatele un nome:

excel21

A questo punto potete chiudere Excel e disinstallarlo. Non serve infatti che Excel sia installato sulla macchina in cui si trova il file che abbiamo appena creato.

Occorre però essere in ambiente Windows, perchè dobbiamo creare un ODBC verso quel file, utilizzando il driver per Excel della Microsoft. Se l’ODBC si chiama TESTODBC, il seguente codice:

Connection con;
Statement stmt;
ResultSet rs;try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
con = DriverManager.getConnection("jdbc:odbc:TESTODBC", "", "");
stmt = con.createStatement();

rs = stmt.executeQuery("SELECT * FROM TABELLAODBC");

while (rs.next()) {
System.out.println(rs.getString(1));
System.out.println(rs.getString(2));
System.out.println(rs.getString(3));
}

}
catch(SQLException e) {
System.out.println("Ops... " + e);
}
catch (ClassNotFoundException cl) {
System.out.println("Ops..." + cl);
}

Restituisce il risultato:

Mario
Bianchi
2
Mario
Rossi
3

Leave a Reply

Your email address will not be published.

You may use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong>