To access this data, we can use the JDBC-ODBC bridge. Microsoft provides an ODBC driver to Excel worksheet. Define an ODBC datasource (system DSN) named "emp_xls" that points to that worksheet. Then compile and run the code below.
You can download the emp.xls file below.
You will probably notice, the code used to pull the records from the worksheet is the same we use for accessing a database, which is basically what we're doing.
=============================================
import java.io.*;
import java.net.*;
import java.sql.*;
import java.util.*;
public class EmployeeReader{
public static final String DRIVER_NAME =
"sun.jdbc.odbc.JdbcOdbcDriver";
public static final String DATABASE_URL = "jdbc:odbc:emp_xls";
public static void main(String[] args)
throws ClassNotFoundException, SQLException{
Class.forName(DRIVER_NAME);
Connection con = null;
try {
con = DriverManager.getConnection(DATABASE_URL);
Statement stmt = con.createStatement();
ResultSet rs = stmt.executeQuery
("select lastname, firstname, id from [Sheet1$]");
while (rs.next()) {
String lname = rs.getString(1);
String fname = rs.getString(2);
int id = rs.getInt(3);
System.out.println(fname + " " + lname + " id : " + id);
}
rs.close();
stmt.close();
}
finally {
if (con != null)
con.close();
}
}
}
| File Attachments: |
|
EMP.XLS (13.5 KB)
|