Home
Manage Your Code
Snippet: ExportToExcel (VB.NET)
Title: ExportToExcel Language: VB.NET
Description: Pass it a datatable, will open up the Excel object and toss in the data. Views: 90
Author: David Smith Date Added: 3/11/2010
Copy Code  
1    Public Sub ExportToExcel(ByVal dt As DataTable)
2        Try
3            Dim oApp As New Microsoft.Office.Interop.Excel.Application
4            Dim oBook As Microsoft.Office.Interop.Excel.Workbook = oApp.Workbooks.Add
5            Dim oSheet As Microsoft.Office.Interop.Excel.Worksheet = CType(oBook.Worksheets(1), Microsoft.Office.Interop.Excel.Worksheet)
6
7            oApp.Visible = False
8
9            Dim iRow As Integer
10            Dim iCol As Integer
11
12
13            With oSheet
14                iRow = 1
15                iCol = 1
16                For Each dc As DataColumn In dt.Columns
17                    Application.DoEvents()
18                    .Cells(iRow, iCol).Value = dc.ColumnName.ToString
19                    .Cells(iRow, iCol).Font.Bold = True
20                    iCol = iCol + 1
21                Next
22
23                iRow = iRow + 1
24                iCol = 1
25                For Each dr As DataRow In dt.Rows
26                    Application.DoEvents()
27                    For Each dc As DataColumn In dt.Columns
28                        Application.DoEvents()
29                        .Cells(iRow, iCol).Value = dr.Item(dc.ColumnName).ToString
30                        iCol = iCol + 1
31                    Next
32                    iRow = iRow + 1
33                    iCol = 1
34                Next
35                oApp.Visible = True
36            End With
37        Catch ex As Exception
38            MessageBox.Show("Source [" & ex.Source & "] Description  [" & ex.Message & "]")
39        End Try
40    End Sub