C#使用oledb连接excel执行Insert Into语句出现“操作必须使用一个可更新的查询”的解决办法
时间:2022-03-10 17:09
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‘
参数Excel 8.0 对于Excel 97以上到2003版本都用Excel 8.0,2007或2010的都用Extended Properties=Excel 12.00 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不行,真是坑爹的节奏啊。
C#使用oledb连接excel执行Insert Into语句出现“操作必须使用一个可更新的查询”的解决办法,布布扣,bubuko.com