0 Replies - 2188 Views - Last Post: 24 January 2016 - 02:37 PM

#1 andrewsw   User is offline

  • Bouncy!
  • member icon

Reputation: 6562
  • View blog
  • Posts: 26,614
  • Joined: 12-December 12

Copy DataGridView to Word

Posted 24 January 2016 - 02:37 PM

Don't forget to Add Reference.. to Word.
Imports Word = Microsoft.Office.Interop.Word  'Add Reference
'Microsoft Word 14.0 Object Library (or 15.0)

    Private Sub btnCopyToWord_Click(sender As Object, e As EventArgs) Handles btnCopyToWord.Click
        Dim wdApp As New Word.Application
        Dim wdDocs As Word.Documents = wdApp.Documents

        wdApp.Visible = True
        Dim wdDoc = wdApp.Documents.Add()
        wdDoc.PageSetup.Orientation = Word.WdOrientation.wdOrientLandscape

        dgvWhatever.ClipboardCopyMode = DataGridViewClipboardCopyMode.EnableAlwaysIncludeHeaderText
        dgvWhatever.SelectAll()
        Clipboard.SetDataObject(dgvWhatever.GetClipboardContent())

        wdDoc.Range.Text = "DataGridView: " & vbCrLf & vbCrLf
        Dim wdRng = wdDoc.Content
        wdRng.Collapse(Word.WdCollapseDirection.wdCollapseEnd)

        wdRng.PasteAndFormat(Word.WdRecoveryType.wdTableAppendTable)

        dgvWhatever.ClearSelection()

        ReleaseObject(wdRng)
        ReleaseObject(wdDoc)
        ReleaseObject(wdDocs)
        ReleaseObject(wdApp)
    End Sub

    Private Sub ReleaseObject(ByVal obj As Object)
        'http://www.siddharthrout.com/2012/08/06/vb-net-two-dot-rule-when-working-with-office-applications-2/
        Try
            System.Runtime.InteropServices.Marshal.ReleaseComObject(obj)
            obj = Nothing
        Catch ex As Exception
            obj = Nothing
        Finally
            GC.Collect()
        End Try
    End Sub

Attached Image

Is This A Good Question/Topic? 0
  • +

Page 1 of 1