在儲存excel檔案時總提示對此目錄沒有操作許可權,於是我又在根目錄的webconfig裡加了一句 <identity impersonate="true" /> .
做了這樣的修改後,產生的檔案可以順利儲存了,但讀取外部excel檔案時總在xlsconn.open()這句出錯;
後來將根目錄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_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;
//測試是否提取資料
//this.Datagrid1.DataSource =ds.Tables["m_tableName"];
//this.Datagrid1.DataBind();
//將Dataset中資料匯入SQL
//AddDatasetToSQL(ds);
}
catch (Exception ex)
{
return null;
}
}
比較簡單的做法是根目錄的Web.Config檔案不加<identity impersonate="true"/>
對有下載檔案的頁面指定許可權:
<location path="forecast/SupplierPlan.aspx">
<system.web>
<identity impersonate="true"/>
</system.web>
</location>