2

以下代码是打开 excel 文件并从中读取,我想处理 excel 文件以便能够删除它:

        Dim strNewPath As String = Server.MapPath("~/UploadedExcel/" & strFileName & strFileType)

        'Connection String to Excel Workbook
        If strFileType.Trim = ".xls" Then
            connString2 = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & strNewPath & ";Extended Properties=""Excel 8.0;HDR=Yes;IMEX=2"""
        ElseIf strFileType.Trim = ".xlsx" Then
            connString2 = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & strNewPath & ";Extended Properties=""Excel 12.0;HDR=Yes;IMEX=2"""
        End If
        query = "SELECT * FROM [Sheet1$]"

        'Create the connection object 
        conn2 = New OleDbConnection(connString2)
        'Open connection
        If conn2.State = ConnectionState.Closed Then conn2.Open()
        'Create the command object
        cmd = New OleDbCommand(query, conn2)
        da = New OleDbDataAdapter(cmd)
        ds = New DataSet()
        da.Fill(ds, "Staff")

        '    up.insertExcel(ds)

        da.Dispose()
4

3 回答 3

3

您应该使用Using-Statement实现的所有内容IDisposable

Using conn2 = New OleDbConnection(connString2)
    conn2.Open()
    Using  cmd = New OleDbCommand(query, conn2)
        Using da = New OleDbDataAdapter(cmd)
            ds = New DataSet()
            da.Fill(ds, "Staff")
        End Using
    End Using
End Using

这确保了对象被释放(即使在异常的情况下)。Dispose也隐式地关闭连接。

于 2012-09-26T07:38:28.143 回答
0

请注意,Command 和 Connection 类也实现 IDisposable 接口。您应该使用“使用”块或 try/finally 语句。在 finally 块中,您必须处理您的对象,即使在出现一些异常的情况下也是如此。

于 2012-09-26T07:21:35.803 回答
0

您拨打电话失败:

conn2.Close();

(或等价物conn2.Dispose()

您应该通过包装一个Using语句来执行此操作,以便即使引发异常也将其关闭:

Using conn2 = New OleDbConnection(...)

    ...

End Using ' conn2 is automatically disposed / closed here
于 2012-09-26T07:22:49.730 回答