C#读取Excel文件时提示:无法指出的错误
做了这样的修改后,生成的文件可以顺利保存了,但读取外部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>