1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40
|
Try
Dim xlApp As Microsoft.Office.Interop.Excel.Application
Dim xlBook As Microsoft.Office.Interop.Excel.Workbook
Dim xlSheet As Microsoft.Office.Interop.Excel.Worksheet
xlApp = CType(CreateObject("Excel.Application"), Microsoft.Office.Interop.Excel.Application)
xlBook = CType(xlApp.Workbooks.Add, Microsoft.Office.Interop.Excel.Workbook)
xlSheet = CType(xlBook.Worksheets(1), Microsoft.Office.Interop.Excel.Worksheet)
' ici on compte le nombre de lignes et de colonnes du datatable
Dim nbrLigne As Integer = ds.Tables("generique").Rows.Count - 1
Dim nbrColon As Integer = ds.Tables("generique").Columns.Count - 1
Dim x, y As Integer
MsgBox("Nombre de colonnes dans la table : " & nbrColon)
MsgBox("Nombre de lignes dans la table : " & nbrLigne)
For x = 0 To nbrColon + 1
' ici on prends le titre des colonnes du datatable
xlSheet.Cells(1, x + 1) = ds.Tables("generique").Columns(x).ColumnName
' on mets la première ligne en gras
xlSheet.Rows(1).Font.Bold = True
' pour chaque colonne et chaque ligne on transfert les données
For y = 1 To nbrLigne
xlSheet.Cells(y + 2, x + 1) = DataGridView1.Item(y, x).Value
Next
Next
' ici on affiche les résultat dans excel
xlSheet.Application.Visible = True
' on peut sauvegarder notre document sur le disque
xlSheet.SaveAs("C:\nom_document.xls")
' on quitte l'application et on détruit les objets
xlApp.Quit()
xlSheet = Nothing
xlBook = Nothing
xlApp = Nothing
Catch ex As System.SystemException
MsgBox(ex.ToString)
Finally
End Try |
Partager