Create a Word Document Dynamically

Imports Microsoft.Office.Interop

Imports Microsoft.Office.Interop.Word

Dim TotalRows As Integer = 50
Dim oApp As Word.Application
Dim oDoc As Word.Document

For Each p As Process In Process.GetProcessesByName(“winword”)
p.Kill()
Next

‘Start a new document in Word
oApp = CType(CreateObject(“Word.Application”), Word.Application)
oDoc = oApp.Documents.Add()

‘ Clear out any existing information.
oDoc.Range.Delete()

‘ Set up the header information.
Dim rng As Word.Range = oDoc.Range(0, 0)
rng.Font.Name = “Verdana”
rng.Font.Size = 16
System.Windows.Forms.Application.DoEvents()
Dim tlb As Word.Table = oDoc.Tables.Add(Range:=rng, NumRows:=TotalRows, NumColumns:=3)

‘Filling data to table
‘Header Row
tlb.Cell(1, 1).Range.Text = “Code”
tlb.Cell(1, 2).Range.Text = “Name”
tlb.Cell(1, 3).Range.Text = “Amount”
tlb.Cell(1, 1).Shading.BackgroundPatternColor = WdColor.wdColorBrown
tlb.Cell(1, 2).Shading.BackgroundPatternColor = WdColor.wdColorBrown
tlb.Cell(1, 3).Shading.BackgroundPatternColor = WdColor.wdColorBrown
‘Data Row
Dim _r() As String = {“”, “8055”, “Sample Item”, “200.00”}
For i As Integer = 2 To TotalRows
For j As Integer = 0 To 3

tlb.Cell(i, j).Range.Text = _r(j)
With (tlb.Cell(i, j).Range.Borders.Item(WdBorderType.wdBorderLeft))

.LineStyle = WdLineStyle.wdLineStyleSingle
.LineWidth = WdLineWidth.wdLineWidth050pt
.Color = WdColor.wdColorAutomatic

End With
With (tlb.Cell(i, j).Range.Borders.Item(WdBorderType.wdBorderBottom))

.LineStyle = WdLineStyle.wdLineStyleSingle
.LineWidth = WdLineWidth.wdLineWidth050pt
.Color = WdColor.wdColorAutomatic

End With
If j = 3 Then
With (tlb.Cell(i, j).Range.Borders.Item(WdBorderType.wdBorderRight))
.LineStyle = WdLineStyle.wdLineStyleSingle
.LineWidth = WdLineWidth.wdLineWidth050pt
.Color = WdColor.wdColorAutomatic

End With
End If
If i = 2 Then
With (tlb.Cell(i, j).Range.Borders.Item(WdBorderType.wdBorderTop))

.LineStyle = WdLineStyle.wdLineStyleSingle
.LineWidth = WdLineWidth.wdLineWidth050pt
.Color = WdColor.wdColorAutomatic

End With
End If
Next
Next

 

oApp.Visible = True

Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s