Export the content of DataGridView to Word Document in vb.net

Several days past i got a comment of my user on the article ‘Create a new Word document using VB.Net‘. He was facing the trouble to export the image to Word document. He wrote his problem as:

I have a Datagridview and all those three fields has been showed in the Datagridview , I have a button Called ” Export to Word”.

There are three columns in the DataGridView, one of them is image type and now we need to export all the content of this Datagridview to the table in the word document. My example contains a DataGridView control named ‘DataGridView1’ that have three columns. Two columns are the TextBox Columns and rest one is of the Image type.

    Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load
        BindGrid()
    End Sub
 
    Private Sub BindGrid()
        DataGridView1.Rows(0).Cells(0).Value = 1
        DataGridView1.Rows(0).Cells(1).Value = "Mohan"
 
        Dim _cellimage As New DataGridViewImageCell
        Try
            DataGridView1.Rows(0).Cells(2).Value = Image.FromFile("D:\Closed.png")
        Catch ex As Exception
 
        End Try
 
    End Sub

There is another button control ‘Export to Document’. On the Click of this button, we will export the content of the datagridview to word document.

    Private Sub btnExport_Click(ByVal sender As System.Object, _
                     ByVal e As System.EventArgs) Handles btnExport.Click
        CreateWordDocument()
    End Sub

The below function will create a word document and export the datagridview.

    Private Sub CreateWordDocument()
        Dim objWord As Word.Application
        Dim objDoc As Word.Document
 
        objWord = CreateObject("Word.Application")
        objWord.Visible = True
        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
 
        For i As Integer = 0 To _RowCount
            ht1.Rows.Add()
            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
        objDoc.SaveAs2("C:/tee.docx")
    End Sub

If you get error in the Following line:
Dim _image As Image = DirectCast(DataGridView1.Rows(i).Cells(_col).Value, Image)

Try to replace this line with the following (Suggested by: Xabier Aberasturi)
(Put “FormattedValue” instead of “Value”)
Dim _image As Image = DirectCast(DataGridView1.Rows(i).Cells(_col).FormattedValue, Image)

10 thoughts on “Export the content of DataGridView to Word Document in vb.net”

  1. Hirendra Once again I am Sorry to disturb you …Actually I’ve Binary Images in the MS Access database and I wanna export Images in png or jpg(format) into Datagridview with Rollno,Name AND then export it all the three fields to word.doc,As You mentioned in the Above Code I’ve tried but the Following error Occurred”Unable to cast object of type ‘System.Byte[]’ to type ‘System.Drawing.Image’.” It is because When I’m Importing Rollno,Name, Image from DB ,the Images in the DGV Is in Binary form and When it export to word.doc it is not showing the Headers ….Please, Please Bro help me Out.I’m waiting.
    And I really thankful for such a great Code.

    1. You need to convert your Byte array to the Image then set the clipboard.

      You can use the code like as shown below:

      Dim memImage As New System.IO.MemoryStream(ImageBytes)
      _image = Image.FromStream(memImage)
      Clipboard.SetImage(_image)
      ht1.Cell(i + 1, _col + 1).Range.Paste()

      thanks

      1. Hirendra , hope you are fine ,. and good…..may God bless you. here again I’ve tackle with the problem. in different Form .where I’ve to read the large (.txt) files in the vb. net form and The txt file contains the RFID based attendance file which has (Rollno,name ,time_in, time_out)
        as you know well RFID reads the student ID twice in a second so in the txt file a single student’s attendance contains more than 3600 times( time_in and time_out ) details per day . here what we have to do is We want only his/her (Rollno ,time_in,time_out) only once at a time like (Rollno=7891011,time_in= 9:00am ,time_out= the last timing which RFID Has read ) and that can be stored in the database………so I’m new to your forum and I’ve searched in the Google but I got some answers which is not supporting for a large amount data. so please bro I’m getting nice answers from you hoping the same again .please kindly acknowledge .

      2. You’re Just Simply Awesome,like ,G.Thank you sooooooooooo much it works for me….thank you thank you.

          1. Yep Bro …Your help made me a perfect Programer .It’s really a great thing you did.may Allah Almighty give you the best of best in this world.

  2. hirendra, please help me!!!!

    Dim memImage As New System.IO.MemoryStream(ImageBytes)
    _image = Image.FromStream(memImage)
    Clipboard.SetImage(_image)
    ht1.Cell(i + 1, _col + 1).Range.Paste()

    in imagebytes give error… help me!!

  3. Hi Hirendra:

    I think there is a bug in your code.
    This line is not correct:
    Dim _image As Image = DirectCast(DataGridView1.Rows(i).Cells(_col).Value, Image)

    That line should be this way:
    (Put “FormattedValue” instead of “Value”)
    Dim _image As Image = DirectCast(DataGridView1.Rows(i).Cells(_col).FormattedValue, Image)

    Anyway, congratulations for your great code !!!!

    Xabier Aberasturi

Comments are closed.