采用ADO.NET存取Excel数据(Use ADO.NET to Retrieve and Modify Records in an Excel Workbook)

我们知道,操作Excel最直接最强有力的方法,是引用Excel的DLL,然后使用包装好的Excel对象体系来执行查找、更新Excel数据,或者一些其他动作。然而如果只是简单地处理一些集合数据,有一种途径可以避免去面对繁杂的Excel对象、各种奇形怪状的变量和函数参数,那就是ADO.NET。以下是微软的一篇知识库文章,详细地说明了如何通过OLE DB连接对Excel数据进行增删改查,其几乎支持所有版本的Excel(我只用到过Excel 2003和Excel 2007)。贴原文的事情就不干了,里面有详细的例子:
http://support.microsoft.com/default.aspx?scid=kb;en-us;316934

需要注意的是,如果你在创建、更新或者删除的时候遇到了这样的异常“Operation must use an updateable query”,可能是如下原因导致的:
1,执行程序不具有对目标Excel进行修改的权限,这种情况的解决方法网上很容易搜索到。
2,连接字符串中设置了“IMEX=1”,很少有人提及此点。且看微软官方的描述:“To work around this problem for read-only data, enable Import Mode by using the setting "IMEX=1" in the Extended Properties section of the connection string. This enforces the ImportMixedTypes=Text registry setting. However, note that updates may give unexpected results in this mode. For additional information about this setting, click the article number below to view the article in the Microsoft Knowledge Base:

194124  (http://support.microsoft.com/kb/194124/EN-US/ ) PRB: Excel Values Returned as NULL Using DAO OpenRecordset ” IMEX设置为1时Excel是被作为只读数据源来看待的!因此对Excel进行创建、更新或者删除的时候一定要记住,去掉IMEX=1选项!请看原文:
http://support.microsoft.com/kb/257819
posted @ 2009-07-22 22:44  Bryan Wong  阅读(1033)  评论(1编辑  收藏  举报