最近需要从Excel导入数据的功能,网上搜索了下代码
public static DataSet GetDataSourceByExcel(string filepath, string sheetname) { string strConn; strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;"; OleDbConnection conn = new OleDbConnection(strConn); OleDbDataAdapter oada = new OleDbDataAdapter("select * from [" + sheetname + "$]", strConn); DataSet ds = new DataSet(); oada.Fill(ds); return ds; } public static ArrayList GetExcelSheetName(string filepath) { ArrayList al = new ArrayList(); string strConn; strConn = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filepath + ";Extended Properties=Excel 8.0;"; OleDbConnection conn = new OleDbConnection(strConn); conn.Open(); DataTable sheetNames = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, new object[] { null, null, null, "TABLE" }); conn.Close(); foreach (DataRow dr in sheetNames.Rows) { al.Add(dr[2]); } return al; }
可能会出现的错误: “The 'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine”
错误原因:
64位的操作系统(包括xp,2003,vista,2008等)在使用OLEDB去访问时回收到下面的一个错误
The 'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine ,问题出在'Microsoft.Jet.OLEDB.4.0' 没有64位的版本。
(Jet的开发已经停止了,所以没有64位的版本。)
解决办法:
1.在对应的 IIS 应用程序池中,“设置应用程序池默认属性”/“常规”/"启用32位应用程序",设置为 true。
估计是Windows 里已经有了 Microsoft.Jet.OLEDB.4.0,32位的,但是默认情况下应用程序池不启用32位程序,所以显示没有安装 “Microsoft.Jet.OLEDB.4.0”。
2.如果是64位平台,也可能出现这种情况;解决方法:(ClassLibary) 属性 - > 生成->配置管理器->平台->点击Any Cpu选项卡->新建->新建平台->X86