2017-07-27 61 views
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 
+2

'对于k为整数= 0要DGVinfo3.Columns.Count + 1'你是不是想要'-1'而不是'+ 1'? – litelite

+0

@litelite仍然同样的问题,仍然给出错误 – Jj84

+0

DGVinfo3.Columns.Count + 1,然后稍后(i + 1,j + 1)。你想达到什么目的?还有(k-1)当k是0时? – n8wrl

回答

0

就环行,并且循环中的每一列。也因为隐藏的列将不会被导出到Excel,它可能是最好的跟踪Excel列在一个单独的变量:

Dim xlColumn As Integer 

    For i = 0 To DGVinfo3.RowCount - 1 
     xlColumn = 0 
     For j = 0 To DGVinfo3.ColumnCount - 1 
       If DGVinfo3.Columns(j).Visible = True Then 
        xlColumn += 1 
        If i = 0 Then 
         'You only need to set the column headers for the first row 
         ExcelWorkSht.Cells(1, xlColumn) = DGVinfo3.Columns(j).HeaderText 
         ExcelWorkSht.Cells(1, xlColumn).Font.Bold = True 
         ExcelWorkSht.Cells(1, xlColumn).interior.color = RGB(192, 203, 219) 
        End If 
        'i + 2 because the header is row 1 
        ExcelWorkSht.Cells(i + 2, xlColumn) = DGVinfo3(i, j).Value 
       End If 
     Next 
    Next 
相关问题