在winform开发中如何把datagrid里面的数据导出成EXCEL文件,网上有好多方法,下面这种是比较快的
Public Sub ExportToExcel(ByVal tb As DataTable)
If DataGrid1.VisibleRowCount > 0 Then
Try
Dim datav As New DataView
datav = tb.DefaultView
Dim i, j As Integer
Dim rows As Integer = datav.Table.Rows.Count
Dim cols As Integer = datav.Table.Columns.Count
Dim DataArray(rows - 1, cols - 1) As String
For i = 0 To rows - 1
For j = 0 To cols - 1
If datav.Table.Rows(i).Item(j) Is System.DBNull.Value Then
Else
DataArray(i, j) = datav.Table.Rows(i).Item(j)
End If
Next
Next
Dim myExcel As Excel.Application = New Excel.Application
myExcel.Application.Workbooks.Add(True)
myExcel.Visible = True
For j = 0 To cols - 1
myExcel.Cells(1, j + 1) = datav.Table.Columns(j).ColumnName
Next
myExcel.Range("A2").Resize(rows, cols).Value = DataArray
Catch exp As Exception
MessageBox.Show("数据导出失败!请查看是否已经安装了Excel", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning)
End Try
Else
MessageBox.Show("没有数据!", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub
WinForm中把DataGrid里面的数据导出成EXCEL文件(VB.net)
最新推荐文章于 2024-09-14 08:25:16 发布