解決C#讀取Excel文件出現(xiàn)無法指出的錯(cuò)誤
在保存excel文件時(shí)總提示對此目錄沒有操作權(quán)限,出現(xiàn)C#讀取Excel文件出現(xiàn)無法指出的錯(cuò)誤。本文將介紹相關(guān)知識(shí)。
在根目錄的webconfig里加了一句 <identity impersonate="true" /> .
做了這樣的修改后,生成的文件可以順利保存了,但讀取外部excel文件時(shí)總在xlsconn.open()這句出錯(cuò);
后來將根目錄webconfig里的<identity impersonate="true" />刪除,加到子目錄excelfile目錄的webconfig里就一切OK了。
- public static DataSet ImportXlsToData(string fileName)
- {
- try
- {
- if (fileName == string.Empty)
- {
- throw new ArgumentNullException("上傳文件失??!");
- }
- //
- string oleDBConnString = String.Empty;
- oleDBConnString = "Provider=Microsoft.Jet.OLEDB.4.0;";
- oleDBConnString += "Data Source=";
- oleDBConnString += fileName;
- oleDBConnString += ";Extended Properties=Excel 8.0;";
- //
- OleDbConnection oleDBConn = null;
- OleDbDataAdapter oleAdMaster = null;
- System.Data.DataTable m_tableName = new System.Data.DataTable();
- DataSet ds = new DataSet();
- try
- {
- oleDBConn = new OleDbConnection(oleDBConnString);
- oleDBConn.Open();
- m_tableName = oleDBConn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
- if (m_tableName != null && m_tableName.Rows.Count > 0)
- {
- m_tableNamem_tableName.TableName = m_tableName.Rows[0]["TABLE_NAME"].ToString();
- }
- string sqlMaster;
- sqlMaster = " SELECT * FROM [" + m_tableName.TableName + "]";
- oleAdMaster = new OleDbDataAdapter(sqlMaster, oleDBConn);
- oleAdMaster.Fill(ds, "m_tableName");
- oleAdMaster.Dispose();
- oleDBConn.Close();
- oleDBConn.Dispose();
- }
- catch (Exception ex)
- {
- ErrorLog.AddLog(ex);
- return null;
- }
- return ds;
- //測試是否提取數(shù)據(jù)
- //this.Datagrid1.DataSource =ds.Tables["m_tableName"];
- //this.Datagrid1.DataBind();
- //將Dataset中數(shù)據(jù)導(dǎo)入SQL
- //AddDatasetToSQL(ds);
- }
- catch (Exception ex)
- {
- return null;
- }
- }
比較簡單的做法是根目錄的Web.Config文件不加<identity impersonate="true"/>
對有下載文件的頁面指定權(quán)限:
- <location path="forecast/SupplierPlan.aspx">
- <system.web>
- <identity impersonate="true"/>
- </system.web>
- </location>
【編輯推薦】
責(zé)任編輯:彭凡
來源:
cnblogs