Creating Word Documents with ASP

Created 13 November 2002 00:00
Using this code you can create a word document which you can then allow your users to download. All you need is to have Word installed on your web server, and to have a template file ( available to the application to open up.
  ' dim variables
  Dim wObject, wDocument

  ' create word document object
  Set wObject = CreateObject("Word.Application")
  ' Set temp word file
  Set wDocument = wObject.Documents.Add(Server.MapPath(".") & "")

  ' choose the font that you want for your document (will default to Times New 
  ' Roman if you leave this out)
  wObject.Selection.Font.Name = "Verdana"
  ' write text to the page
  wObject.Selection.TypeText("Plain verdana")
  ' new paragraph
  ' insert page break 
  ' add picture to document
  wObject.Selection.InlineShapes.AddPicture Server.MapPath(".") & "" & "picName.gif"
  ' change the size of the font
  wObject.Selection.Font.Size = 10
  ' change the colour and style of the font
  wObject.Selection.Font.ColorIndex = 2
  wObject.Selection.Font.Bold = True
  wObject.Selection.Font.Italic = False
  ' justify the new parapgraph in the word document (0=left, 1=center, 2=right)
  wObject.Selection.ParagraphFormat.Alignment = 1

  ' save document
  wDocument.SaveAs Server.MapPath(".") & "Output.doc"

  ' quit the word application - very important to prevent multiple 
  ' instances of Word running on the server.  Best approach is to 
  ' have an On Error Resume Next on this page so this line is always 
  ' executed - rather manually trap errors.

  ' clean up
  Set rs = Nothing
  Set wObject = Nothing
  Set wDocument = Nothing
Inserting tables into word documents

You need to create tables into a range in the document - generally I find the easiest way is to have a document template with a bookmark already created in the template. In the following example, a bookmark called "TEST" is created, and the range used is the range of that bookmark. Assuming "obj" is a reference to a running word application object:

  Dim doc       ' word document
  Dim tbl       ' table you are going to create
  Set doc = obj.Documents.Open("D:\Matt\Test.doc")
  Set tbl = doc.Tables.Add(doc.Bookmarks("TEST").Range, 3, 5)
  tbl.Cell(1, 1).Range.Text = "hello"
or alternatively, if you don't want to use bookmarks and just want to add tables to the end of a document, use the paragraph object's range:
  Dim oPar as Word.Paragraph
  Dim oTable as Word.Table
  ' add first table
  Set oPar = oDoc.Paragraphs.Add()
  Set oTable = oDoc.Tables.Add(oPar.Range, 3, 5)
  ' add second table
  Set oPar = oDoc.Paragraphs.Add()
  Set oTable = oDoc.Tables.Add(oPar.Range, 3, 5)