将DataGridView导出到Excel文件缺失行

时间:2014-04-01 18:45:55

标签: vb.net excel export-to-excel

我使用此代码将datagridview导出到excel但总是错过一行,如果datagridview返回单行,则excel只返回没有单行的标题 导出代码是

Dim rowsTotal, colsTotal As Short
        Dim I, j, iC As Short
        System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.WaitCursor
        Dim xlApp As New Excel.Application
        Try
            Dim excelBook As Excel.Workbook = xlApp.Workbooks.Add
            Dim excelWorksheet As Excel.Worksheet = CType(excelBook.Worksheets(1), Excel.Worksheet)
            xlApp.Visible = True

            rowsTotal = DataGridView1.RowCount - 1
            colsTotal = DataGridView1.Columns.Count - 1
            With excelWorksheet
                .Cells.Select()
                .Cells.Delete()
                For iC = 0 To colsTotal
                    .Cells(1, iC + 1).Value = DataGridView1.Columns(iC).HeaderText
                Next
                For I = 0 To rowsTotal - 1
                    For j = 0 To colsTotal
                        .Cells(I + 2, j + 1).value = DataGridView1.Rows(I).Cells(j).Value
                    Next j
                Next I
                .Rows("1:1").Font.FontStyle = "Bold"
                .Rows("1:1").Font.Size = 12

                .Cells.Columns.AutoFit()
                .Cells.Select()
                .Cells.EntireColumn.AutoFit()
                .Cells(1, 1).Select()
            End With
        Catch ex As Exception
            MessageBox.Show(ex.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error)
        Finally
            'RELEASE ALLOACTED RESOURCES
            System.Windows.Forms.Cursor.Current = System.Windows.Forms.Cursors.Default
            xlApp = Nothing
        End Try

1 个答案:

答案 0 :(得分:0)

抱歉,但我找到了答案。 答案是从

删除-1
For I = 0 To rowsTotal - 1
  For j = 0 To colsTotal
     .Cells(I + 2, j + 1).value = DataGridView1.Rows(I).Cells(j).Value
  Next j
Next I

For I = 0 To rowsTotal 
      For j = 0 To colsTotal
         .Cells(I + 2, j + 1).value = DataGridView1.Rows(I).Cells(j).Value
      Next j
    Next I