簡體   English   中英

從Excel文件讀取數據:代碼未進入Catch()塊

[英]Reading data from excel file: Code not going into Catch() block

我正在編寫代碼以從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()”

如果文件打開,我不確定查詢是否失敗。 也許它只是在等待...您可以像這樣測試這種情況: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

結束功能

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM