C#使用oledb连接excel运行Insert Into语句出现“操作必须使用一个可更新的查询”的解决的方法

我错误发生时的环境:Windows 7,Framework 4、0,Microsoft Office 2007,VS2010,c# WinForm。
部分代码:
                    string strConn = "Provider=Microsoft.Ace.OleDb.12.0;Persist Security Info=False;" + "data source=" + @excelPath + ";Extended Properties='Excel 12.0; HDR=yes; IMEX=2'";
                    OleDbConnection conn = new OleDbConnection();
                    conn.ConnectionString = strConn;
                    try
                    {
                        OleDbCommand cmd = null;
                        try
                        {
                            cmd = new OleDbCommand("Insert Into [Sheet1$] Values('abc', 'bac', '0', '123456', 'test','測试','aa')", conn);//(A,B,C,D,E,F,G) 
                            cmd.ExecuteNonQuery();
                        }
                        catch (System.Exception ex)
                        {
                            textBox1.Text += ("插入数据失败:" + ex.Message);
                            textBox1.Text += ("\r\n");
                        }
遇到此错误的时候第一想到的就是没有权限,但使用管理员身份执行依旧是同样的错误。
又通过下面代码加入权限,还是一样的错误:
FileInfo fi = new FileInfo(excelPath);
System.Security.AccessControl.FileSecurity fileSecurity = fi.GetAccessControl();
fileSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
fileSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
fi.SetAccessControl(fileSecurity);

DirectoryInfo di = new DirectoryInfo(Path.GetDirectoryName(excelPath));
System.Security.AccessControl.DirectorySecurity dirSecurity = di.GetAccessControl();
dirSecurity.AddAccessRule(new FileSystemAccessRule("Everyone", FileSystemRights.FullControl, AccessControlType.Allow));
dirSecurity.AddAccessRule(new FileSystemAccessRule("Users", FileSystemRights.FullControl, AccessControlType.Allow));
di.SetAccessControl(dirSecurity);
知识补习。这里的连接字符串多了:Extended Properties='Excel 12.0; HDR=yes; IMEX=2'

參数HDR的值:

HDR=Yes。这代表第一行是标题。不做为数据使用 。假设用HDR=NO,则表示第一行不是标题。做为数据来使用。系统默认的是YES
參数Excel 8.0 对于Excel 97以上到2003版本号都用Excel 8.0,2007或2010的都用Extended Properties=Excel 12.0
IMEX ( IMport EXport mode )设置
  IMEX 有三种模式:
  0 is Export mode
  1 is Import mode
  2 is Linked mode (full update capabilities)
  我这里特别要说明的就是 IMEX 參数了。由于不同的模式代表著不同的读写行为:
  当 IMEX=0 时为“汇出模式”,这个模式开启的 Excel 档案仅仅能用来做“写入”用途。
  当 IMEX=1 时为“汇入模式”,这个模式开启的 Excel 档案仅仅能用来做“读取”用途。
  当 IMEX=2 时为“连結模式”,这个模式开启的 Excel 档案可同一时候支援“读取”与“写入”用途。


意义例如以下:
0 ---输出模式;
1---输入模式;
2----链接模式(全然更新能力)

依照以上描写叙述,上面的连接字符串应该是能够读取,插件记录的
可是事实并不是如此,当执行Insert Into语句时却出现异常:“操作必须使用一个可更新的查询”!


注意是c# WinForm程序,不是Web应用程序;假设是Web应用程序。那须要加入IIS_IUSRS或IIS_Service用户的文件夹訪问权限;
还是去搜索看看别人是怎么解决的吧,可是看遍了别人解决这个问题的方法,到我这里就是測试不通过!
推測还是IMEX值的问题,改为1不行。那就改为0,尼马,奇迹出现了! 
接着又測试将IMEX设置为4或10,结果都没问题,只有1和2不行。真是坑爹的节奏啊。
posted @ 2017-05-16 17:32  claireyuancy  阅读(2114)  评论(0编辑  收藏  举报