Java读取Excel文件
1.通过JDBC访问工作表,首先创建一个新的ODBC数据源,在Windows xp系统上创建数据源的过程如下:进入“设置/控制面板/性能和维护/管理工具/数据源(ODBC),点击“添加”,在弹出窗口中选择“Driver do Microsoft Excel(*.xls)”,然后在数据源名处输入一个名字Book1(相当于数据库名),然后点击“选择工作簿”,然后找到并选取你的Excel文件,点击确定完成配置。
2.代码:
import java.sql.Connection;
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.DriverManager;
public class Test {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Book1", "",
"");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM [Sheet1$]");
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1) // 用逗号分隔各列
System.out.print(", ");
String columnvalue = rs.getString(i);
System.out.print(columnvalue);
}
System.out.println("");
}
st.close();
con.close();
} catch (Exception ex) {
System.err.print("Exception: ");
System.err.println(ex.getMessage());
}
}
}
import java.sql.Statement;
import java.sql.ResultSet;
import java.sql.ResultSetMetaData;
import java.sql.DriverManager;
public class Test {
public static void main(String[] args) {
try {
Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");
Connection con = DriverManager.getConnection("jdbc:odbc:Book1", "",
"");
Statement st = con.createStatement();
ResultSet rs = st.executeQuery("SELECT * FROM [Sheet1$]");
ResultSetMetaData rsmd = rs.getMetaData();
int numberOfColumns = rsmd.getColumnCount();
while (rs.next()) {
for (int i = 1; i <= numberOfColumns; i++) {
if (i > 1) // 用逗号分隔各列
System.out.print(", ");
String columnvalue = rs.getString(i);
System.out.print(columnvalue);
}
System.out.println("");
}
st.close();
con.close();
} catch (Exception ex) {
System.err.print("Exception: ");
System.err.println(ex.getMessage());
}
}
}