MS-Word Mail Merge component for Delphi 5

MS-Word Mail Merge component for Delphi 5


1. Description
2. Requirements
3. Sample scenario
4. Methods and properties
5. Download the freeware component
6. Updates
7. Resources
8. About the author

1. Description

I made this small component because I needed mail merge capabilities in an application, and I couldn't find a free component on the internet. The component has been tested in Word'97 and Word 2000.

Via this component, your application can easily create Word documents with application generated contents. The component will open a Word template file (document), and link (merge) the field data from your application to a new generated document.

2. Requirements

The component requires Delphi 5, and the Delphi 5 Office Automation Servers. The office automation servers will be used internally by the component.

3. Sample scenario and code

Suppose that you have a database application with a customer table, a product table, and a sales table. You run a query which shows all customers which have ordered something, but they have not paid there bills yet. Now you want to send them a letter (a real paper letter in an enveloppe) to inform them about their debts.
Follow these steps to accomplish the task:
  1. Start Word, and open or create a document.
  2. Insert mailmerge fields on locations where you want database fields: menu "Insert -> Field. A form appears with 2 listboxes and an input field which contains the text "=". Replace the "=" by the text "Mergefield FirstName". Firstname is your own field name, we will use this fieldname in the Delphi application. Close the form by activating the "OK" button. The text <> appears in your document.
  3. The rest of the Word stuff is easy now you know how to insert fields in your document. Finish up your document with some more fields and text, and close it.
  4. Put the MailMerge unit in the Uses list of your Delphi unit.
    Create the component and setup the properties. Set the 'columns' property to something like 'firstname;lastname;amountdue;employeename'. Add all records from your query to the component:
        MailMerge.Columns := 'firstname;lastname;amountdue;employeename';
        YourQuery.First;
        while not YourQuery.EOF do
        begin
          MailMerge.Append;
          MailMerge['firstname'] := sqlYourQueryFirstname.Value; // (from a TStringField component)
          MailMerge['lastname'] := sqlYourQueryLastname.Value;
          MailMerge['employeename'] := tblSession.EmployeeName;
          //etc
        end;
        
  5. Set the document name property in your component, eg:
        MailMerge.DocumentName := 'c:\my documents\test merge.doc';
      
  6. Optionally, set the OnStatusMessage event:
        MailMerge.OnStatusMessage := MailMergeStatusMessage;
        .....
        procedure MailMergeStatusMessage(Sender: TObject);
        begin
          StatusBar1.SimpleText := TMailMerge(Sender).StatusMessage;
        end;
      
  7. Start the mail merge:
        MailMerge.Merge;
      
    Word will launch, and a temporary datasource document will be generated by the component. The template will be opened and merged with the datasource document. The result comes in a new document, and can be accessed via the component's WordDoc interface. (Eg: MailMerge.WordDoc.Print and MailMerge.WordDoc.Close)

4. Methods and Properties

property RecordCount The amount of appended records, read only
property Columns A string of columns, seperated by semicolumns. Eg: 'firstname;lastname;employeename'
property ColumnCount The amount of columns, read only
property FieldValues[const FieldName: string] Set or read the value of a field.
property DocumentName The complete path of a Word template document
property StatusMessage The current status message, ReadOnly
property WordApplication Interface to the Word Application object (TWordApplication)
property WordDocument Interface to the generated Word Document (_Document)
property DataSource mdHTML, mdTabs, or mdDirectTable
event OnStatusMessage Triggered when a new status message is available. See also: property StatusMessage
constructor Create Obvious
destructor Destroy Obvious
procedure Append Adds a newrecord to the component. See also: property FieldValues
procedure Clear Clears all fields and columns data in memory, and clears the DocumentName
procedure Merge Starts the mail merge

5. Download the freeware component

MailMerge.zip can be downloaded here (19 KB for component + 220 KB for demos)

A demo application is included. There is no 'register' procedure, just create the component runtime or add your own register function...

6. Updates

August 23 2000 Component created (version 1.0)
August 24 2000 Publicly released
August 30 2000 Keith Blows added a major speed improvement to the component, it's now 20 times faster than before (by removing Word tables from the datasource and using tabs instead). Thanks Keith!
September 1, 2000 Again by Keith Blows: The component will now generate a HTML file with tables, and Word will convert the HTML to a DOC. This is much faster and you can still have fields with tabs and carriage return characters. Tested with over a 1000 records. The previous datasource generation methods are still present, set the DataSource property to mdHTML(default), mdTabs, or mdDirectTable. However, mdHTML is strongly recommended because it is the fastest way.
October 11, 2000 Bug fix: after closing Word you coulnd't merge again.
March 3, 2001 Speed improvement: Appending records is now faster.

Svilen Ivanov solved a bug in the mdDirectTable merge method. Due to column widths of 100, Word would return a "Value out of range" error when you have more than 15 fields. The field width is now set to 10 instead of 100 to solve this problem.


I won't make much changes to this component, maybe a few extra features will be added which I need for my application and some bug fixes. If you make modifications to the component, then I'd like to receive a copy so I can place it on this page (robert@ionosphere.nl).

7. Resources

I gathered info from these sites:
Deborah Pate's site: Office Automation for Delphi
Microsoft article about Mail Merge via Delphi
Updated Delphi Help of Office servers

8. About the author

My name is Robert van Tilburg and I live in the Netherlands. I'm 21 years old and a computer science student. I learned programming on a MSX-1 homecomputer when I was 10 years old. Now I have various part-time Delphi programming jobs, and experience with Delphi, Turbo Pascal, Basic, 32 bits assembler, C++, C++ Builder, Databases (paradox, Access, SQL Server via BDE and ADO), DirectX, Internet, and desktop applications.

EMail: robert@ionosphere.nl

Back to my components index page

Published on Torry's Delphi Pages

Page stats -->