0

我正在编写代码以从 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()”

4

1 回答 1

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

结束功能

于 2012-11-20T07:24:21.443 回答