1.package com.mysql.odbc; 2.import java.sql.Connection; 3.import java.sql.DriverManager; 4.import java.sql.PreparedStatement; 5.import java.sql.ResultSet; 6.import java.sql.SQLException; 7.import java.sql.Statement; 8. 9.public class OdbcExcel { 10.private final String DRIVERCLASSNAME = "sun.jdbc.odbc.JdbcOdbcDriver"; 11.private Connection con = null; 12.// 注:連接字符串必須加上readonly=false屬性,不然沒法修改.更多選項看參照Access數據源配置的高級選項. 13.// 更多連接字符串可在 http://www.connectionstrings.com 上查看. 14.// Driver={Microsoft Excel Driver (*.xls)};DriverId=790;Dbq=C:\MyExcel.xls;DefaultDir=c:\mypath; 15.private String url = "jdbc:odbc:Driver={Microsoft Excel Driver (*.xls)};DBQ=Test..xls;READONLY=FALSE"; 16. 17.public OdbcExcel() throws Exception { 18. Class.forName(DRIVERCLASSNAME); 19. con = DriverManager.getConnection(url); 20. 21.} 22. 23.public int write() throws Exception { 24. Statement statement = con.createStatement(); 25. // 建立一個工做簿(表),使用完後必定要關閉,不然會出錯! 26. int x = statement.executeUpdate("create table 測試(編號 NUMBER,用戶名 TEXT)"); 27. statement.close(); 28. return x; 29.} 30. 31.public void read() throws SQLException { 32. Statement statement = con.createStatement(); 33. /** 34. * 查詢時代表應該用 [tablename$] 或[worksheetname$] 這是微軟ODBC的保留字,否測會出現找不到引擎. 35. * Excel會把首行的值當成字段值.即列名. SQL syntax "SELECT * FROM [sheet1$]". I.e. 36. * excel worksheet name followed by a "$" and wrapped in "[" "]" 37. * brackets. 38. * */ 39. ResultSet result = statement.executeQuery("SELECT * FROM [測試$]"); 40. while (result.next()) { 41. System.out.println(result.getInt(1) + "\t" + result.getString(2)); 42. } 43. result.close(); 44.} 45. 46.public int update() throws SQLException { 47. Statement statement = con.createStatement(); 48. int x = statement.executeUpdate("insert into 測試 values(1,'孟德軍')"); 49. /** 50. * int x = statement.executeUpdate("insert into 測試 values(1,'孟德軍')"); 51. * String sql="alter table 測試 add 密碼 TEXT"; 52. * */ 53. statement.close(); 54. return x; 55.} 56. 57.public void close() throws SQLException { 58. // 必定要關閉鏈接對象,不然文檔會出錯. 59. 60. if (con != null) { 61. con.close(); 62. } 63.} 64. 65.public static void main(String[] args) throws Exception { 66. OdbcExcel excel = new OdbcExcel(); 67. // 建立工做簿(表) 68. excel.write(); 69. // 寫入一條數據 70. excel.update(); 71. // 讀取寫入的數據 72. excel.read(); 73. // 關閉對象 74. excel.close(); 75.} 76. 77.}