如何在vb.net中读取excel文件
下面的代码是打开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()
对于实现IDisposable
所有内容,您应该使用Using-Statement
:
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
也隐式closures连接。
你没有打电话给:
conn2.Close();
(或等效的conn2.Dispose()
)
你应该通过包装在一个Using
语句中,以便即使抛出一个exception也closures它:
Using conn2 = New OleDbConnection(...) ... End Using ' conn2 is automatically disposed / closed here
请注意,Command和Connection类也实现了IDisposable接口。 你应该使用“使用”块或try / finally语句。 在finally块中,即使出现一些exception,也必须处理对象。