You are on page 1of 2

C:\DataTableToExcel.

vb jeudi 14 avril 2011 14:36

Imports System.IO
Imports System.Text
Imports System
Imports System.Data
Imports System.Data.OleDb
Imports Excel = Microsoft.Office.Interop.Excel

Public Shared Function DataTableToExcel(ByVal dt As DataTable, _


Optional ByVal colvisible() As Integer = Nothing,
_
Optional ByVal visibleHeader As Boolean = True)
As String
Try

'Ajouter l'Utilsateur ASPNET au groupe Administrateurs(pour evité Accés refusé) : click droit poste travail -> Gérer ->
Utilisateurs et groupes locaux -> Groupes ...
'colvisible : les colonnes visibles
If IsNothing(colvisible) Then
colvisible = New Integer() {0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 13, 14,
15, 16, 17, 18, 19, 20}
End If

Dim xlApp As Excel.Application


Dim xlWorkBook As Excel.Workbook
Dim xlWorkSheet As Excel.Worksheet

xlApp = New Excel.ApplicationClass


xlWorkBook = xlApp.Workbooks.Add(1)
xlWorkSheet = xlWorkBook.Sheets.Item(1)

Dim colindex As Integer = 1


Dim startRow As Integer = 1

If visibleHeader Then
startRow = 2
For j As Integer = 0 To dt.Columns.Count - 1
If colvisible.IndexOf(colvisible, j) <> -1 Then
xlWorkSheet.Cells(1, colindex).value = dt.Columns(j).ColumnName
colindex += 1
End If
Next
End If

For i As Integer = 0 To dt.Rows.Count - 1


colindex = 1
For j As Integer = 0 To dt.Columns.Count - 1
If colvisible.IndexOf(colvisible, j) <> -1 Then
xlWorkSheet.Cells(i + startRow, colindex).value = dt.Rows(i).Item(j).
ToString
colindex += 1
End If
Next
Next

Dim filename As String = fcts.Generer_Code() & ".xls"

xlWorkSheet.SaveAs("\Inetpub\wwwroot\" + fcts.mEtat + "\Download\Excel\" &

-1-
C:\DataTableToExcel.vb jeudi 14 avril 2011 14:36

filename)

xlWorkBook.Close()
xlApp.Quit()

releaseObject(xlApp)
releaseObject(xlWorkBook)
releaseObject(xlWorkSheet)

Return filename

Catch ex As Exception
Return ""
End Try
End Function

Private Shared Sub releaseObject(ByVal obj As Object)


Try
System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
obj = Nothing
Catch ex As Exception
obj = Nothing
Finally
GC.Collect()
End Try
End Sub

-2-