Importer Datagridview a Word

Résolu
wayne2017 Messages postés 57 Date d'inscription jeudi 23 février 2017 Statut Membre Dernière intervention 10 mai 2017 - 9 mai 2017 à 11:34
wayne2017 Messages postés 57 Date d'inscription jeudi 23 février 2017 Statut Membre Dernière intervention 10 mai 2017 - 10 mai 2017 à 21:10
Bonjour,
je voudrais importer ma datagridview dans un fichier Word mais a chaque fois le code me dit ceci : Impossible d'effectuer un cast d'un objet de type 'System.Data.DataSet' en type 'System.Data.DataTable'. s'il vous plait pourriez me dire ou ce trouve l'erreur merci bien



Dim datatabl As New System.Data.DataTable
datatabl = DataGridViewMachine.DataSource

Dim oWord = New Word.Application With {.Visible = True}
Dim oDocs As Word.Document = oWord.Documents.Open("D:\sample.docx")
Dim otable As Word.Table
otable = oDocs.Tables.Add(oDocs.Bookmarks.Item("\endofdoc").Range, datatabl.Rows.Count + 1, datatabl.Columns.Count)
For c = 0 To datatabl.Columns.Count - 1
otable.Cell(1, c + 1).Range.Text = datatabl.Columns(c).ToString
Next

For r = 0 To datatabl.Rows.Count - 1
For c = 0 To datatabl.Columns.Count - 1
otable.Cell(r + 2, c + 1).Range.Text = datatabl.Rows(r).Item(c).ToString
Next
Next
otable.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle
otable.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle
oDocs.Close(SaveChanges:=True)
oDocs = Nothing
oWord.Quit()
oWord = Nothing
GC.Collect()
GC.WaitForFullGCComplete()



4 réponses

cs_Le Pivert Messages postés 7903 Date d'inscription jeudi 13 septembre 2007 Statut Contributeur Dernière intervention 11 mars 2024 137
Modifié le 9 mai 2017 à 17:52
Voilà avec une base Access:


Option Strict On
Imports System.Data.OleDb
Imports Microsoft.Office.Interop
Imports Microsoft.Office.Interop.Word
Public Class Form1
    Private Sub Button1_Click(sender As System.Object, e As System.EventArgs) Handles Button1.Click
        'Mise en place d'un objet OpenFileDialog pour ouvrir un fichier 
        Dim openFD As New OpenFileDialog
        With openFD
            .Filter = "Access Files  (*.accdb,*.mdb )|*.accdb;*.mdb"
            .FilterIndex = 1
            .Title = "Sélectionnez le fichier Access que vous souhaitez ouvrir."
            DialogResult = .ShowDialog
            If DialogResult = System.Windows.Forms.DialogResult.OK Then
                Dim ds As New DataSet()
                ds.Clear()
                DataGridView1.Columns.Clear()
                ' Cheminsource = (.FileName) 'chemin complet fichier source
                ' Please be sure of the database path, I suppose it will be in the same folder where the application exe file is in (usually should be in 'YourProjectPath\bin\debug')
                Dim MyConnectionString As String = "Provider=Microsoft.Jet.OLEDB.4.0; Data Source=" & .FileName
                ' Generating the DataSet and the DataAdapter

                ' All 'Customers' table's columns could fit in one page
                Dim da As OleDbDataAdapter = New OleDbDataAdapter("SELECT * FROM Customers", MyConnectionString)
                ' All 'Customers2' table's columns could fit in two page
                'Dim da As New OleDbDataAdapter("SELECT * FROM Customers2", MyConnectionString)
                Try
                    da.Fill(ds, "dt")
                Catch ex As Exception
                    MessageBox.Show("Operation failed: " + ex.ToString(), " - Error", MessageBoxButtons.OK, MessageBoxIcon.[Error])
                    Return
                End Try

                ' Setting the style of the DataGridView control
                'DataGridView1.ColumnHeadersDefaultCellStyle.Font = New Font("Tahoma", 9, FontStyle.Bold, GraphicsUnit.Point)
                DataGridView1.ColumnHeadersDefaultCellStyle.BackColor = SystemColors.ControlDark
                DataGridView1.ColumnHeadersBorderStyle = DataGridViewHeaderBorderStyle.[Single]
                DataGridView1.ColumnHeadersDefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleCenter
                ' DataGridView1.DefaultCellStyle.Font = New Font("Tahoma", 8, FontStyle.Regular, GraphicsUnit.Point)
                DataGridView1.DefaultCellStyle.BackColor = Color.Empty
                DataGridView1.AlternatingRowsDefaultCellStyle.BackColor = SystemColors.ControlLight
                DataGridView1.CellBorderStyle = DataGridViewCellBorderStyle.[Single]
                DataGridView1.GridColor = SystemColors.ControlDarkDark

                ' Binding the DataGridViewControl to the DataSet generated above
                DataGridView1.DataSource = ds
                DataGridView1.DataMember = "dt"

                ' Changing the last column alignment to be in the Right alignment            
                DataGridView1.Columns(DataGridView1.Columns.Count - 1).DefaultCellStyle.Alignment = DataGridViewContentAlignment.MiddleRight

                ' Adjusting each column to be fit as the content of all its cells, including the header cell
                DataGridView1.AutoResizeColumns(DataGridViewAutoSizeColumnsMode.AllCells)

                'DataGridView1.Columns[0].Visible = false;
            Else
                MessageBox.Show("Opération annulée par l'utilisateur!", "Chemin fichier", MessageBoxButtons.OK, MessageBoxIcon.Information)
                Exit Sub
            End If
            .Dispose()
        End With
    End Sub
    Private Sub Importer()
        Dim objWord = New Word.Application With {.Visible = True}
        Dim objDoc As Word.Document = objWord.Documents.Open("C:\Users\LePivert\Documents\essai.docx")

        'objDoc = objWord.Documents.Add

        Dim _RowCount As Integer = DataGridView1.Rows.Count - 1
        Dim _ColCount As Integer = DataGridView1.Columns.Count - 1

        Dim ht1 As Word.Table

        ht1 = objDoc.Tables.Add(objDoc.Bookmarks.Item("\endofdoc").Range, _
                                _RowCount + 1, _ColCount + 1)
        ht1.Borders.OutsideColor = Word.WdColor.wdColorBlack
        ht1.Borders.OutsideLineStyle = Word.WdLineStyle.wdLineStyleSingle
        ht1.Borders.InsideColor = Word.WdColor.wdColorBlack
        ht1.Borders.InsideLineStyle = Word.WdLineStyle.wdLineStyleSingle
        Try
            For i As Integer = 0 To _RowCount
                For _col As Integer = 0 To _ColCount
                    Dim colType As Type = DataGridView1.Columns(_col).GetType
                    If colType.Name = "DataGridViewImageColumn" Then
                        Dim _image As Image = DirectCast(DataGridView1.Rows(i).Cells(_col).Value, Image)
                        Clipboard.SetImage(_image)
                        ht1.Cell(i + 1, _col + 1).Range.Paste()
                    Else
                        ht1.Cell(i + 1, _col + 1).Range.Text = DataGridView1.Rows(i).Cells(_col).Value.ToString()
                    End If
                Next
            Next
        Catch
        End Try
    End Sub
    Private Sub Button2_Click(sender As System.Object, e As System.EventArgs) Handles Button2.Click
        Importer()
    End Sub
End Class


il suffit de chercher et d'adapter!

http://www.authorcode.com/export-the-content-of-datagridview-to-word-document-in-vb-net/

@+ Le Pivert
1
wayne2017 Messages postés 57 Date d'inscription jeudi 23 février 2017 Statut Membre Dernière intervention 10 mai 2017
10 mai 2017 à 21:08
J'ai su adapter en parallèle avec un autre programme il marche bien , merci encore
0
cs_Le Pivert Messages postés 7903 Date d'inscription jeudi 13 septembre 2007 Statut Contributeur Dernière intervention 11 mars 2024 137
9 mai 2017 à 11:56
0
wayne2017 Messages postés 57 Date d'inscription jeudi 23 février 2017 Statut Membre Dernière intervention 10 mai 2017
9 mai 2017 à 11:59
Bonjour CS_Le Pivert

j'ai changer de méthode .car j'ai opter créer séparément
0
cs_Le Pivert Messages postés 7903 Date d'inscription jeudi 13 septembre 2007 Statut Contributeur Dernière intervention 11 mars 2024 137 > wayne2017 Messages postés 57 Date d'inscription jeudi 23 février 2017 Statut Membre Dernière intervention 10 mai 2017
9 mai 2017 à 12:06
Je dois te rappeler que nous sommes tous des bénévoles. Il serait bon d'avoir la politesse de répondre aux réponses qui te sont faites!
C'est la moindre des choses, si tu veux que l'on continue à te suivre!
0
wayne2017 Messages postés 57 Date d'inscription jeudi 23 février 2017 Statut Membre Dernière intervention 10 mai 2017 > cs_Le Pivert Messages postés 7903 Date d'inscription jeudi 13 septembre 2007 Statut Contributeur Dernière intervention 11 mars 2024
9 mai 2017 à 12:14
D'accord j'ai compris , je ferais bien ca
0
wayne2017 Messages postés 57 Date d'inscription jeudi 23 février 2017 Statut Membre Dernière intervention 10 mai 2017
9 mai 2017 à 21:54
Merci le cs _Le Pivert
0
wayne2017 Messages postés 57 Date d'inscription jeudi 23 février 2017 Statut Membre Dernière intervention 10 mai 2017
10 mai 2017 à 21:10
0
Rejoignez-nous