将excel单元格数据写入datagridview单元格(visual basic)

时间:2013-12-10 16:33:54

标签: vb.net excel loops datagridview

我遍历列并在列循环中循环遍历行。我的excel文件的布局方式是列是每个日期,行包括各种值的各个数据。问题是dataviewgrid没有填充我的excel文件中的值。这是我的循环

' Get the Excel application object.
    excel_app = New Excel.Application

    ' Make Excel visible (optional).
    excel_app.Visible = False

    ' Open the workbook.
    workbook = excel_app.Workbooks.Open("C:\Users\Michael Jr\Desktop\iBudgetBuddy\Records.xlsx", , True)
    sheet_name = "Sheet1"

    sheet = excel_app.Worksheets("Sheet1")

    Dim ColumnCount, RowCount As Long
    ColumnCount = sheet.Range("A1").CurrentRegion.Columns.Count
    RowCount = sheet.Range("A1").CurrentRegion.Rows.Count

    DataGridView1.ColumnCount = ColumnCount
    DataGridView1.RowCount = RowCount
    DataGridView1.ColumnHeadersVisible = False
    DataGridView1.RowHeadersVisible = False

    **For ecIndex As Integer = 0 To ColumnCount
        Dim drIndex As Integer = 0
        Dim dcolumnIndex As Integer = 0
        For erIndex As Integer = 0 To RowCount
            DataGridView1.Rows(drIndex).Cells(dcolumnIndex).Value = sheet.Cells(erIndex, ecIndex).Value
            erIndex = erIndex + 1
            drIndex = drIndex + 1
        Next
        dcolumnIndex = dcolumnIndex + 1
        ecIndex = ecIndex + 1
    Next**

End Sub

知道为什么它不起作用吗?

*的 修改 * 我已经能够成功地让程序读取并创建行和列。它填充第一列,即行所包含的标题(示例收入,费用)。但是,它不会填充第二列中的任何内容。为什么会这样做?我编辑的循环看起来像这样

    For cIndex As Integer = 0 To ColumnCount

        For rIndex As Integer = 0 To RowCount
            DataGridView1.Rows(rIndex).Cells(cIndex).Value = sheet.Range("A1").Offset(rIndex, cIndex).Value()
        Next

    Next

0 个答案:

没有答案