2017-07-27 108 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 
相關問題