Quantcast
Channel: Open XML Format SDK forum
Viewing all articles
Browse latest Browse all 1288

Merged documents openxml mailmerge

$
0
0

I am a chemistry graduate and very new to programming, having learned everything from the Internet. I have a Word document with mail merge fields. The data source is an Excel file. I want to change the datasource Excel file dynamically and save the the merged document in a new file.

public static void mergeDocs() {
    string fileToOpen = @"D:\CSharpProjects\MailMerge\document.docx";
    using (WordprocessingDocument wordDocument = WordprocessingDocument.Open(fileToOpen, true))
    {
        int mailmergecount = wordDocument.MainDocumentPart.DocumentSettingsPart.Settings.Elements<MailMerge>().Count();
        Console.WriteLine ("Number of mail merges:{0}",  mailmergecount);
        MailMerge mymerge = wordDocument.MainDocumentPart.DocumentSettingsPart.Settings.Elements<MailMerge>().First();
        mymerge.ConnectString.Val = "Provider=Microsoft.ACE.OLEDB.12.0;User ID=Admin;Data Source=D:\\CSharpProjects\\MailMerge\\Data.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 Locking Mode=0;Jet OLEDB:Global Partial Bulk Ops=2;Jet OLEDB:Global Bulk Transactions=1;Jet OLEDB:New Database Password=\"\";Jet OLEDB:Create System Database=False;Jet OLEDB:Encrypt Database=False;Jet OLEDB:Don\'t Copy Locale on Compact=False;Jet OLEDB:Compact Without Replica Repair=False;Jet OLEDB:SFP=False;Jet OLEDB:Support Complex Data=False";
        foreach
        (var relationship in wordDocument.ExternalRelationships.Where(Rel =>
        Rel.RelationshipType == "http://schemas.openxmlformats.org/officeDocument/2006/relationships/mailMergeSource"))
        { wordDocument.DeleteExternalRelationship(relationship); }
        string DataPath = @"D:\CSharpProjects\MailMerge\data1.xlsx";
        var dsRelationship = wordDocument.MainDocumentPart.DocumentSettingsPart.AddExternalRelationship("http://schemas.openxmlformats.org/officeDocument/2006/relationships/mailMergeSource", new Uri(string.Format("file:///{0}", DataPath)));                 
        mymerge.DataSourceReference.Id = dsRelationship.Id;
        mymerge.ViewMergedData.Val = true;
    }

This changes the datasource, but I need to manually finish the merge and save the merged document. How do I automate this process?


Viewing all articles
Browse latest Browse all 1288

Trending Articles



<script src="https://jsc.adskeeper.com/r/s/rssing.com.1596347.js" async> </script>