Public
Function ExportExcel(ByVal dgv As DataGridView, ByVal IsOnlyVisible As Boolean) As Boolean
Try
Dim n, i, j, row, col As Integer
Dim excel As Excel.Application = New Excel.Application()
excel.Application.Workbooks.Add(True)
col = 1
'//记录列名
For n = 0 To dgv.ColumnCount - 1
If IsOnlyVisible Then
If dgv.Columns(n).Visible Then
excel.Cells(1, col) = dgv.Columns(n).HeaderText
col = col + 1
End If
Else
excel.Cells(1, n + 1) = dgv.Columns(n).HeaderText
End If
Next
'//记录内容
row = 2
' col = 1
For i = 0 To dgv.RowCount - 1
col = 1
For j = 0 To dgv.ColumnCount - 1
'System.Windows.Forms.Application.DoEvents()
If IsOnlyVisible Then
If dgv.Columns(j).Visible Then
excel.Cells(i + 2, col) = dgv.Rows(i).Cells(j).Value
col = col + 1
End If
Else
excel.Cells(i + 2, j + 1) = dgv.Rows(i).Cells(j).Value
End If
Next
Next
excel.Visible = True
Catch ex As Exception
Throw ex
End Try
End Function
Try
Dim n, i, j, row, col As Integer
Dim excel As Excel.Application = New Excel.Application()
excel.Application.Workbooks.Add(True)
col = 1
'//记录列名
For n = 0 To dgv.ColumnCount - 1
If IsOnlyVisible Then
If dgv.Columns(n).Visible Then
excel.Cells(1, col) = dgv.Columns(n).HeaderText
col = col + 1
End If
Else
excel.Cells(1, n + 1) = dgv.Columns(n).HeaderText
End If
Next
'//记录内容
row = 2
' col = 1
For i = 0 To dgv.RowCount - 1
col = 1
For j = 0 To dgv.ColumnCount - 1
'System.Windows.Forms.Application.DoEvents()
If IsOnlyVisible Then
If dgv.Columns(j).Visible Then
excel.Cells(i + 2, col) = dgv.Rows(i).Cells(j).Value
col = col + 1
End If
Else
excel.Cells(i + 2, j + 1) = dgv.Rows(i).Cells(j).Value
End If
Next
Next
excel.Visible = True
Catch ex As Exception
Throw ex
End Try
End Function