我錯誤發生時的環境: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
參數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 檔案可同一時候支援“讀取”與“寫入”用途。
依照以上描寫敘述,上面的連接字符串應該是能夠讀取,插件記錄的
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不行。真是坑爹的節奏啊。
