1

把自己撑在一个角落里......

使用了我在网上找到的一段代码,但无法弄清楚如何关闭此连接。返回的 OleDbcommand objCommand 在处理后保持打开状态。我需要将其关闭,以便在从中提取数据后删除该文件。(不希望他们在服务器上闲逛。)

这必须比我尝试执行的 100 行代码更容易。该函数打开连接。

Protected Function ExcelConnection() As OleDbCommand
    Dim fileName As String = Session("newUploadedFile")

    ' Connect to the Excel Spreadsheet
    Dim xConnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
          "Data Source=" & Server.MapPath(String.Format("~/Upload/{0}", fileName)) & ";" & _
          "Extended Properties=Excel 8.0;"

    ' create your excel connection object using the connection string
    Dim objXConn As New OleDbConnection(xConnStr)
    objXConn.Open()
    ' use a SQL Select command to retrieve the data from the Excel Spreadsheet
    ' the "table name" is the name of the worksheet within the spreadsheet
    ' in this case, the worksheet name is "Sheet1" and is expressed as: [Sheet1$]

    Dim objCommand As New OleDbCommand("SELECT Name FROM [Sheet1$]", objXConn)

    Return objCommand
End Function

我试过了...

  ExcelConnection.connection.close()

以及大约 40 次其他尝试重新创建命令然后关闭它。

真的可以在这方面使用一些帮助。

4

1 回答 1

1

这可能不是最好的方法,但如果您真的必须这样做,请考虑在调用例程中定义和打开连接,并将其作为参数传递给该例程。然后可以在调用路由中关闭它,因此......

Sub Main()

    Dim xConnStr As String = "Provider=Microsoft.ACE.OLEDB.12.0;" & _
        "Data Source=" & Server.MapPath(String.Format("~/Upload/{0}", fileName)) & ";" & _
        "Extended Properties=Excel 8.0;"

    Dim objXConn As New OleDbConnection(xConnStr)
    objXConn.Open()
    Dim ObjCommand As New OleDbCommand = ExcelConnection(objXConn)

    'Whatever other operations you want to do with your returned OleDbCommand
    ...

    objXConn.Close()

End Sub

Function ExcelConnection(PassedConnection As OleDbConnection) As OleDbCommand
    Dim fileName As String = Session("newUploadedFile")
    Dim objCommand As New OleDbCommand("SELECT Name FROM [Sheet1$]", PassedConnection)
    Return objCommand
End Function

我在这里发布了与此类似的内容...阅读 Excel 工作表的最快方法

于 2013-01-15T22:51:05.150 回答