1
我有一个数据网格视图,我想导出到Excel。 我想仅导出数据网格视图中的可见列。'索引超出范围。必须是非负数并小于集合的大小
但我不断收到此错误。
Private Sub btnExport_Click(sender As Object, e As EventArgs) Handles btnExport.Click
Dim ExcelApp As Excel.Application
Dim ExcelWorkBk As Excel.Workbook
Dim ExcelWorkSht As Excel.Worksheet
Dim i As Integer
Dim j As Integer
ExcelApp = New Excel.Application
ExcelWorkBk = ExcelApp.Workbooks.Add()
ExcelWorkSht = ExcelWorkBk.Sheets("Sheet1")
Dim columnsCount As Integer = DGVinfo3.Columns.Count
For i = 0 To DGVinfo3.RowCount - 1
If DGVinfo3.Columns(i).Visible = True Then
For j = 0 To DGVinfo3.ColumnCount - 1
For k As Integer = 0 To DGVinfo3.Columns.Count + 1
If DGVinfo3.Columns(k).Visible = True Then
ExcelWorkSht.Cells(1, k) = DGVinfo3.Columns(k - 1).HeaderText
ExcelWorkSht.Cells(1, k).Font.Bold = True
ExcelWorkSht.Cells(1, k).interior.color = RGB(192, 203, 219)
ExcelWorkSht.Cells(i + 1, j + 1) = DGVinfo3(j, i).Value
End If
Next
Next
End If
Next
End Sub
我不断收到此错误:
System. Argument Out Of Range Exception: 'Index was out of range. Must be non-negative and less than the size of the collection.'
这里就是我得到的错误:
ExcelWorkSht.Cells(1, k) = DGVinfo3.Columns(k - 1).HeaderText
'对于k为整数= 0要DGVinfo3.Columns.Count + 1'你是不是想要'-1'而不是'+ 1'? – litelite
@litelite仍然同样的问题,仍然给出错误 – Jj84
DGVinfo3.Columns.Count + 1,然后稍后(i + 1,j + 1)。你想达到什么目的?还有(k-1)当k是0时? – n8wrl