简体   繁体   中英

Mail merge in C# with n copies

I just want to create a C# program which will read a word template and create n number of copies of it with mail merge feature.The data to replace is Name and Address the rest of the things in the template should remains the same. Can any one tell me how to do this ?

You can use Aspose.Word for handling the Word Object model without having to have office installed (to use interop) where the program is supposed to run, i'm using Aspose.Word to generate word documents.

Link to Aspose: http://www.aspose.com/categories/file-format-components/aspose.words-for-.net-and-java/default.aspx

And it works quite decent :)

I did this in Java - (broken link) working example here with source code.

Here's the idea: use MS-Word to design and construct the document you want to send. Save it as XML (either Word-ML or the new .docx format). Then, using a text editor, replace the fields in the document with placeholder tags, like @@NAME where the name should go, and @@ADDRESS for the Address, etc. The tag names don't matter.

Then, build a replacement logic - either using XSLT or even a simple string-based replace function, and iteratively replace the tags with actual data values. Save each modified doc.

Easy peasy.

You could use the same design in C# - actually it would be EASIER.

I am not sure whether you wish to run a mailmerge or to copy a template. I cannot help you with c#, but this snippet of VBA might give you some ideas.

 strDir = CurrentProject.Path  

 strMailmergeDataFilename = strDir & Format(Now, "yymmdd_hhnnss") & ".txt"

' Create CSV from database for use with mailmerge '
' This is a separate function that simply exports the sql '
' ExportSQLToCSV SQL, strMailmergeDataFilename '

'Open merge template '
Set objWordDoc = GetObject(strDir & MergeDocumentFilename, "Word.Document")

objWordDoc.Application.Visible = True      

'Format:=0 ''0 = wdOpenFormatAuto'
'Add the data source '
objWordDoc.MailMerge.OpenDataSource _
    Name:=strMailmergeDataFilename, ConfirmConversions:=False, _
    ReadOnly:=False, LinkToSource:=True, AddToRecentFiles:=False, _
    PasswordDocument:="", PasswordTemplate:="", WritePasswordDocument:="", _
    WritePasswordTemplate:="", Revert:=False, Format:=0, _
    Connection:="", SQLStatement:="", SQLStatement1:=""

'Type some text at a bookmark, you could use .range property ' 
Selection.Goto What:=wdGoToBookmark, Name:="signaturetext"
Selection.TypeText Text:="You are here"

'Run mailmerge '
objWordDoc.MailMerge.Destination = 0 '0 = wdSendToNewDocument'

objWordDoc.MailMerge.Execute

objWordDoc.Application.ActiveDocument.PrintPreview

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM