|
发表于 2020-8-20 20:45:01
|
显示全部楼层
Public Sub ExportToExcel()
If DataGrid1.VisibleRowCount > 0 Then
Try
Dim ds As New DataSet
ds = DataGrid1.DataSource
Dim i, j As Integer
Dim rows As Integer = ds.Tables(0).Rows.Count
Dim cols As Integer = ds.Tables(0).Columns.Count
Dim DataArray(rows - 1, cols - 1) As String
For i = 0 To rows - 1
For j = 0 To cols - 1
If ds.Tables(0).Rows(i).Item(j) Is System.DBNull.Value Then
Else
DataArray(i, j) = ds.Tables(0).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) = ds.Tables(0).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
|
|