Tag Archives: word programming in .net

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)

Print word document programmatically in .net

 
We can use can use the PrintOut method to print a Microsoft Office Word document, following example code shows how to print whole word document in vb.net and c# languages:

Code Sample :

[vb.net]

    Private Sub PrintWordDocument()
        Dim objWord As Word.Application
        Dim objDoc As Word.Document
        objWord = CreateObject("Word.Application")
        objDoc = objWord.Documents.Open("D:\Test.docx")
        objDoc.PrintOut()
        objDoc.Close()
        objDoc = Nothing
        objWord.Quit()
    End Sub

[c#]

 private void PrintWordDocument()
        {
            object objMissing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word.Application objWord;
            Microsoft.Office.Interop.Word.Document objDoc;
            objWord = new Microsoft.Office.Interop.Word.Application();
            object fileName = @"D:\Test.docx";
            objDoc=objWord.Documents.Open(ref fileName,
                ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing,
                ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing,
                ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing);
 
            object copies = "1";
            object pages = "";
            object range = Microsoft.Office.Interop.Word.WdPrintOutRange.wdPrintAllDocument;
            object items = Microsoft.Office.Interop.Word.WdPrintOutItem.wdPrintDocumentContent;
            object pageType = Microsoft.Office.Interop.Word.WdPrintOutPages.wdPrintAllPages;
            object objTrue = true;
            object objFalse = false;
 
            objDoc.PrintOut(
                ref objTrue, ref objFalse, ref range, ref objMissing, ref objMissing, ref objMissing,
                ref items, ref copies, ref pages, ref pageType, ref objFalse, ref objTrue,
                ref objMissing, ref objFalse, ref objMissing, ref objMissing, ref objMissing, ref objMissing);
        }

How to print current page of active word document in .net

 
We can use can use the PrintOut method to print a Microsoft Office Word document, following example code shows how to print one copy of the current page of the word document in vb.net and c# languages:

Code Sample :

[vb.net]

Private Sub PrintCurrentpageInWordDocument()
        Dim objWord As Word.Application
        Dim objDoc As Word.Document
        objWord = CreateObject("Word.Application")
        objDoc = objWord.Documents.Open("D:\Test.docx")
        objDoc.PrintOut(Background:=True, Append:=False, _
                        Range:=Word.WdPrintOutRange.wdPrintCurrentPage, _
                       Item:=Word.WdPrintOutItem.wdPrintDocumentContent, _
                       Copies:="1", Pages:="1", PageType:=Word.WdPrintOutPages.wdPrintAllPages, _
                       PrintToFile:=False, Collate:=True, ManualDuplexPrint:=False)
        objDoc.Close()
        objDoc = Nothing
        objWord.Quit()
 End Sub

[c#]

 private void PrintCurrentpageInWordDocument()
        {
            object objMissing = System.Reflection.Missing.Value;
            Microsoft.Office.Interop.Word.Application objWord;
            Microsoft.Office.Interop.Word.Document objDoc;
            objWord = new Microsoft.Office.Interop.Word.Application();
            object fileName = @"D:\Test.docx";
            objDoc=objWord.Documents.Open(ref fileName,
                ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing,
                ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing,
                ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing);
 
            object copies = "1";
            object pages = "1";
            object range = Microsoft.Office.Interop.Word.WdPrintOutRange.wdPrintCurrentPage;
            object items = Microsoft.Office.Interop.Word.WdPrintOutItem.wdPrintDocumentContent;
            object pageType = Microsoft.Office.Interop.Word.WdPrintOutPages.wdPrintAllPages;
            object objTrue = true;
            object objFalse = false;
 
            objDoc.PrintOut(
                ref objTrue, ref objFalse, ref range, ref objMissing, ref objMissing, ref objMissing,
                ref items, ref copies, ref pages, ref pageType, ref objFalse, ref objTrue,
                ref objMissing, ref objFalse, ref objMissing, ref objMissing, ref objMissing, ref objMissing);
        }

How to find Count of total Characters in word document programmatically

 
If you want to get count of total characters in any word document at run time in .net, you can use following code samples.

Code Sample :

[vb.net]
vb.net code for finding count of characters in word document.

Private Function GetCharectorsCount() As Integer
        Dim objWord As Word.Application
        Dim objDoc As Word.Document
        objWord = CreateObject("Word.Application")
        objDoc = objWord.Documents.Open("D:\Test.docx")
        Dim TotalCount As Integer = objDoc.Characters.Count
        Return TotalCount
    End Function

[c#]
C# code for finding count of characters in word document.

    private static int  GetWordCharacters()
        {
            object objMissing = System.Reflection.Missing.Value;
 
            Microsoft.Office.Interop.Word._Application objWord;
            Microsoft.Office.Interop.Word._Document objDoc;
            objWord = new Microsoft.Office.Interop.Word.Application();
 
            object fileName = @"D:\Test.docx";
 
            objDoc=objWord.Documents.Open(ref fileName,
                ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing,
                ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing,
                ref objMissing, ref objMissing, ref objMissing, ref objMissing, ref objMissing);
            int totalCount = objDoc.Characters.Count;
            return totalCount;
        }

Note:

All characters in the document are counted, including spaces, paragraph marks, and other characters that are normally hidden. Even a new, blank document returns a count of one character because it contains a paragraph mark.

How to open existing word document in vb.net

 

This example shows how to open an existing word document in vb.net.
Add reference of ‘Microsoft.Office.Interop.Word’ in your project.
This code example requires a document named Test.docx must exist in a D: drive.

Code Sample :

Private Sub OpenWordDocument()
        Dim objWord As Word.Application
        Dim objDoc As Word.Document
        objWord = CreateObject("Word.Application")
        objDoc = objWord.Documents.Open("D:\Test.docx")
        objWord.Visible = True
End Sub

Create a new Word document and insert a table using VB.Net

 
This article describes how to create a new Word document and insert a table using VB.Net, it also shows how to format tables, and populate the tables with data.

follow these steps:
1. Start a new Windows application in vb.net language.
2. Add a reference to the Microsoft Word Object Library
3. Add a button to Form1 from Toolbox.
4. Double-click Button1, create a Button click event.
5. Write code on the click event of button:

Private Sub Button1_Click(ByVal sender As System.Object,
                              ByVal e As System.EventArgs) Handles Button1.Click
        CreateTableInWordDocument()
End Sub
Private Sub CreateTableInWordDocument()
        Dim objWord As Word.Application
        Dim objDoc As Word.Document
        Dim objTable As Word.Table
        objWord = CreateObject("Word.Application")
        objWord.Visible = True
        objDoc = objWord.Documents.Add
        Dim r As Integer, c As Integer
 
        objTable = objDoc.Tables.Add(objDoc.Bookmarks.Item("\endofdoc").Range, 3, 5)
        objTable.Range.ParagraphFormat.SpaceAfter = 6
        For r = 1 To 3
            For c = 1 To 5
                objTable.Cell(r, c).Range.Text = "Row" & r & " Coulmn" & c
            Next
        Next
        objTable.Rows.Item(1).Range.Font.Bold = True
        objTable.Rows.Item(1).Range.Font.Italic = True
        objTable.Borders.Shadow = True
        Me.Close()
    End Sub