|
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("Data export failed! Please check whether Excel has been installed", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Warning)
End Try
Else
MessageBox.Show("No data!", Me.Text, MessageBoxButtons.OK, MessageBoxIcon.Information)
End If
End Sub |
|