vb.net遍历一个xls / xlsx文件?

在vb.net中有一个简单的方法来加载一个Excel文件并阅读它? 也许有一种方法来加载文件,但不能被用户看到?

亚历克斯 – 这里是我挖掘查询Excel的一些旧代码。 这里很基本的场景。 不要关注糟糕的error handling和缺less“使用”结构。

Dim connString As String = "Provider=Microsoft.Jet.OLEDB.4.0" & _ ";Data Source=" & ExcelFile & _ ";Extended Properties=Excel 8.0;" Dim conn As OleDbConnection = Nothing Dim dt As System.Data.DataTable = Nothing Dim excelDataSet As New DataSet() Try conn = New OleDbConnection(connString) conn.Open() dt = conn.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, Nothing) If dt Is Nothing Then Return Nothing End If Dim excelSheets(dt.Rows.Count) As String Dim i As Integer = 0 For Each row As DataRow In dt.Rows excelSheets(i) = row("TABLE_NAME").ToString System.Math.Min(System.Threading.Interlocked.Increment(i), i - 1) If i = SheetNumber Then Exit For End If Next Using excelCommand As New OleDbCommand("Select * from [" & excelSheets(SheetNumber - 1) & "]", conn) Using excelAdapter As New OleDbDataAdapter(excelCommand) excelAdapter.Fill(excelDataSet) End Using End Using Catch ex As OleDbException Throw Catch ex As Exception Throw Finally conn.Close() If conn IsNot Nothing Then conn.Dispose() End If If dt IsNot Nothing Then dt.Dispose() End If End Try Return excelDataSet 

直接从.NET使用Excel对象模型 。

您可以使用ado.net通过OLEDB JET 4提供程序从Excel电子表格中读取数据

这只是打开Excel文件作为文件stream,而不是打开实际的Excel电子表格。

或者,您可以使用com-interop,并简单地将应用程序对象可见属性设置为false。

请参阅http://www.connectionstrings.com/excel

在使用.net和com与任何办公应用程序互操作时,需要注意的一点是,如果您尝试以比实际的人类用户更多的Windows服务作为用户来打开应用程序,那么您将需要以这种方式login到Windows用户并以该用户的身份打开相关应用程序,以便所有registry项都正确更新,以便办公应用程序的某些function。

如果你有一个更简单(即小)的Excel电子表格,不需要是dynamic的,我想你可以导出为一个逗号分隔的文件,然后使用循环和streamreader对象来parsing每个逗号分隔值到一个数组。

虽然有点儿…