Wednesday, May 24, 2006

Create a quick report in Word

Sometimes I just want to create a very quick report for a client but I don't want to deal with the complexity of setting up a report in a tool like Crystal Reports or SQL Reporting Services.

What I have found works well is to create a Word template with the report headers and footers that I want, and then simply create all the report lines as a large string and then just have the application paste that text into a blank instance of that template.

Sample code follows:

Dim sb as new System.Text.StringBuilder

... place here all the statements needed to create the report data as a large string in sb ...

Dim oWord As Object
oWord = CreateObject("Word.Application")
oWord.Visible = True
oWord.Documents.Open("MyReportTemplate.dot")
oWord.activedocument.bookmarks.add("Top").select()
oWord.selection.typetext(sb.ToString)
Application.DoEvents()

Note that this is only for very simple reports because it does not allow for any formatting within the text or within the document header or footer. Note that a tab is chr(9) and a form-feed (new page) is chr(12).

Often time clients just want the data and don't mind doing the formatting themselves in MS Word when it is finished.

Hope you find this tip useful...
Joe Kunk

SQL Reporting Services and Word are registered trademarks of Microsoft Corporation.
Crystal Reports is a registered trademark of Business Objects SA.

1 comment:

Joe Kunk said...

Follow-up: I have found that there is a limited amount of text that can be pasted with this process. It is best to repeat the oword.typetext command at the end of each page. By flushing the text at the end of each page, I have been successful in creating reports of over 1,000 pages using this technique.