【问题标题】:Populate a 2D array from a dataset imported from excel using data without column headers使用不带列标题的数据从从 excel 导入的数据集中填充二维数组
【发布时间】:2020-05-01 17:19:15
【问题描述】:

我正在尝试使用不带列标题的数据从从 excel 导入的数据集中填充数组。我的代码如下:

Dim conn As OleDbConnection
Dim dta As OleDbDataAdapter
Dim dts As DataSet
Dim excel As String

Private Sub Button2_Click(sender As Object, e As EventArgs) Handles Button2.Click
    Try

        Dim OpenFileDialog As New OpenFileDialog
        With OpenFileDialog
            .InitialDirectory = My.Computer.FileSystem.SpecialDirectories.MyDocuments
            .Filter = "All Files (*.*) | *.*"

            If .ShowDialog(Me) = System.Windows.Forms.DialogResult.OK Then
                Dim fi As New IO.FileInfo(.FileName)
                Dim FileName As String = .FileName
                excel = fi.FullName
                Dim connString As String = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" & excel & ";Extended Properties=""Excel 12.0 Xml;HDR=NO;IMEX=1"""
                conn = New OleDbConnection(connString)
                dta = New OleDbDataAdapter("Select * from [Sheet1$]", conn)
                dts = New DataSet
                dta.Fill(dts, "[Sheet1$]")
                Dim arrCol0 As Double() = (From myRow In dts.Tables(0).AsEnumerable
                                           Select myRow.Field(Of Double)("[A]")).ToArray
                conn.Close()
            End If
        End With

    Catch ex As Exception
        MsgBox(ex.Message)
        conn.Close()
        Exit Sub
    End Try
End Sub

"Select myRow.Field(Of Double)("[A]")" 中的 [A] 似乎是必需的。有没有办法排除列标题?

【问题讨论】:

  • 使用序数。像:dim theColumnIndex as integer = 1 dim arrCol0 = dts.Tables(0).AsEnumerable().Select(function(r) Convert.ToDouble((r(theColumnIndex))).ToArray()r.Field(Of Double)(theColumnIndex) 就可以了。顺便说一句,如果您只需要一个 DataTable,请填写 DataTable 而不是 DataSet。
  • 谢谢吉米。与 DataSet 相比,DataTable 有什么好处?
  • 您正在使用数据表。您对 DataSet 什么都不做。由于您实际上并没有使用它,因此添加开销是没有用的:只需填写一个 DataTable。

标签: excel vb.net dataset oledb


【解决方案1】:

您将根据DataTable 中的列数和行数创建数组,然后通过列索引和行索引遍历DataTable 和数组,例如

Dim arr(table.Columns.Count - 1, table.Rows.Count - 1) As Double

For columnIndex = 0 To arr.GetUpperBound(0)
    For rowIndex = 0 To arr.GetUpperBound(1)
        arr(columnIndex, rowIndex) = CDbl(table.Rows(rowIndex)(columnIndex))
    Next
Next

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-06-26
    • 2014-06-16
    • 1970-01-01
    相关资源
    最近更新 更多