将Excel范围加载到VB DataGridView中

时间:2014-01-24 16:31:30

标签: vb.net excel datagridview

VB新手。我正在尝试将8000行VBA宏转换为VB。我刚开始,我相信我会在这里寻求很多帮助。

我正在尝试将Excel范围加载到DataGridView中。将数组添加为数据源后,DataGridView保持空白。我错过了什么?

Dim xlApp As New Excel.Application
Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet

Private Sub Button2_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button2.Click
    xlWorkBook = xlApp.Workbooks.Open("C:\Users\me\Dropbox\Test\Test.xls")
    xlWorkSheet = xlApp.Sheets("TestPage")
    Dim loadArray(,) As Object = xlWorkSheet.Range("B15:N22").Value
    DataGridView1.DataSource = loadArray
    xlApp.Visible = False
    xlApp.Quit()
End Sub

感谢您的帮助。

1 个答案:

答案 0 :(得分:0)

而不是DataGridView1.DataSource = loadArray,我会试试这个。它将在datagridview中为“B-N”创建一个列,并使用电子表格中的单元格值填充datagridview的行(假设loadarray正确加载了数据)。

For i As Integer = 0 To 12  '0 = B to 12 = N
    dataGridView1.Columns.Add(i.ToString(), i.ToString())
    For j As Integer = 0 To 6
        If i = 0 Then
            dataGridView1.Rows.Add()
        End If
        dataGridView1.Rows(j).Cells(i).Value = loadArray(i,j)
    Next
Next

HTH