Mail Merge (Excel to Word) using C#

无人久伴 提交于 2019-12-23 01:18:06

问题


I was wondering if anybody knew how to do a mail merge using an Excel file as a datasource, to fill in fields on a Word template? I wish to use the interop for Word if i could...but am having a few difficulties finding code for this. Does anybody have any syntax for this? Thank you in advance.


回答1:


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.




回答2:


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?




回答3:


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



来源:https://stackoverflow.com/questions/884988/mail-merge-excel-to-word-using-c-sharp

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