日期:2014-05-16  浏览次数:20475 次

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