我正在编写代码以从 excel 文件中读取数据。早些时候,如果我已经打开了 Excel 文件,我的代码会进入“Catch()”块,并为其抛出异常。现在,它不会抛出异常,但需要很长时间才能读取。我想知道为什么它不在“Catch()”块中。
代码:
DataTable VendorCodesTable = new DataTable("VendorCodesData");
DataTable ForSheetName = new DataTable("ForSheetName");
string SheetName = "Sheet1$";
try
{
ExcelConnectionString = string.Format("Provider=Microsoft.Jet.OLEDB.4.0; data source={0}; Extended Properties=Excel 8.0;", fileName);
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ExcelConnectionString;
conn.Open();
ForSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (ForSheetName != null)
{
SheetName = ForSheetName.Rows[0]["TABLE_NAME"].ToString();
}
conn.Close();
OleDbDataAdapter adapter = new OleDbDataAdapter("SELECT * FROM ["+SheetName+"]", ExcelConnectionString);
adapter.Fill(VendorCodesTable);
}
catch (Exception ex)
{
MessageBox.Show(ex.ToString(), "Exception");
}
return VendorCodesTable;
我添加了这段代码,它停止抛出错误,并且花了很长时间来加载文件:
OleDbConnection conn = new OleDbConnection();
conn.ConnectionString = ExcelConnectionString;
conn.Open();
ForSheetName = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);
if (ForSheetName != null)
{
SheetName = ForSheetName.Rows[0]["TABLE_NAME"].ToString();
}
conn.Close();
现在,即使我评论上面的行,它也不会进入“Catch()”