Mail Merge (Excel to Word) using C#

自闭症网瘾萝莉.ら 提交于 2019-12-08 03:46:27

A very useful method for learning how to automate specific actions in MS Word is to actually perform the action manually with 'Record Macro' enabled.

Once you have the VBA macro its easy enough to convert this to VB.NET or C# that uses interop. I tend to tweak the VBA first manually in Word so I can then test this first before converting to a .NET language using the interop layer.

I don't know much about mailmerge, but this is some of the VBA generated whilst I recorded a macro:

ActiveDocument.MailMerge.MainDocumentType = wdFormLetters
ActiveDocument.MailMerge.OpenDataSource Name:= _
    "c:\Arrays.xlsx", ConfirmConversions:=False, _
     ReadOnly:=False, LinkToSource:=True, AddToRecentFiles:=False, _
    PasswordDocument:="", PasswordTemplate:="", WritePasswordDocument:="", _
    WritePasswordTemplate:="", Revert:=False, Format:=wdOpenFormatAuto, _
    Connection:= _
    "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=c:\Arrays.xlsx;Mode=Read;Extended Properties=""HDR=YES;IMEX=1;"";Jet OLEDB:System database="""";Jet OLEDB:Registry Path="""";Jet OLEDB:Engine Type=37;Jet OLEDB:Database Loc" _
    , SQLStatement:="SELECT * FROM `Sheet1$`", SQLStatement1:="", SubType:= _
    wdMergeSubTypeAccess

I haven't included the full code here, but hopefully this give you some ideas.

Word (at least in the 2007 version, which is what I'm looking at) can do this out of the box. Just select the Excel file as the datasource. What are you trying to do in your code?

I use this 3rd party control. You can read your xls file into a data table and then tell the control to merge it.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!