我正在编写代码来从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()'
答案 0 :(得分:0)
如果文件打开,我不确定查询是否失败。也许只是等待...... 您可以像这样测试这种情况: VB.NEt代码:
Private Function FileIsReadable(Path As String) As Boolean
Dim RV As Boolean = True
'tests if the file is open. Returns true if the file is not opened by excel.
Dim stream As IO.FileStream = Nothing
Try
stream = IO.File.Open(Path, IO.FileMode.Open, IO.FileAccess.ReadWrite, IO.FileShare.None)
Catch ex As Exception
If TypeOf ex Is IO.IOException AndAlso IsFileLocked(ex) Then
RV = False
End If
Finally
If IsNothing(stream) = False Then
stream.Dispose()
End If
End Try
Return RV
结束功能