MSWord自动化合并也打印模板文档

本文关键字:文档 打印 自动化 合并 MSWord | 更新日期: 2023-09-27 18:29:37

。。。使用vs2010和自动化office 2007

合并工作正常,但保存的文档(pathToDestinationFile)将原始文档(pathToTemplate)附加为第二页。我已经验证了pathToTemplate只是一个单页文档。pathToDB和pathToHdr是用作合并数据的纯文本文件。我做错了什么?

public void MergeWordTemplate(bool displayApp, string pathToTemplate, string pathToDB, string pathToHdr, string pathToDestinationFile)
{
    Word._Application wrdApp = null;;
    Word._Document mrgDoc = null, newDoc = null;
    try
    {
        wrdApp = new Word.Application();
        wrdApp.Visible = displayApp;
        //open the template
        mrgDoc = wrdApp.Documents.Add(pathToTemplate, ref oMissing, ref oMissing, ref oMissing);
        if (mrgDoc.MailMerge.Fields != null && mrgDoc.MailMerge.Fields.Count == 0)
            throw new Exception(string.Format("Template '"{0}'" does not contain any merge fields.", System.IO.Path.GetFileName(pathToTemplate)));
        //open the data file
        mrgDoc.MailMerge.OpenDataSource(pathToDB);
        mrgDoc.MailMerge.OpenHeaderSource(pathToHdr);
        mrgDoc.MailMerge.Destination = Word.WdMailMergeDestination.wdSendToNewDocument;
        //merge
        mrgDoc.MailMerge.Execute(ref oFalse);
        newDoc = wrdApp.ActiveDocument;
        try
        {                    
            if (!string.IsNullOrWhiteSpace(pathToDestinationFile) && Directory.Exists(Path.GetDirectoryName(pathToDestinationFile)))
                newDoc.SaveAs(pathToDestinationFile);
        }
        catch
        {
            wrdApp.Visible = true;
        }
        //get out
        mrgDoc.Saved = true;
        mrgDoc.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges);
        KillCOM(mrgDoc);
        newDoc.Saved = true;
        newDoc.Close(Microsoft.Office.Interop.Word.WdSaveOptions.wdDoNotSaveChanges);
        KillCOM(newDoc);
        wrdApp.Quit(ref oFalse, ref oMissing, ref oMissing);
        KillCOM(wrdApp);
        mrgDoc = null;
        newDoc = null;
        wrdApp = null;
    }
    catch (Exception e)
    {
        KillCOM(mrgDoc);
        KillCOM(newDoc);
        KillCOM(wrdApp);
        mrgDoc = null;
        newDoc = null;
        wrdApp = null;
        //todo: log exceptions here
        string err = e.ToString();
    }
}

MSWord自动化合并也打印模板文档

解决方案是调用MailMerge.Execute(),就好像这有任何意义一样。

关键的部分。。。。

    //open the data file
mrgDoc.MailMerge.OpenHeaderSource(pathToHdr);
mrgDoc.MailMerge.OpenDataSource(pathToDB);
mrgDoc.MailMerge.SuppressBlankLines = true;
mrgDoc.MailMerge.ViewMailMergeFieldCodes = 0;
mrgDoc.Application.ActiveDocument.Range(0, 0).Select();                
try
{
    if (!string.IsNullOrWhiteSpace(pathToDestinationFile) && Directory.Exists(Path.GetDirectoryName(pathToDestinationFile)))
    mrgDoc.SaveAs(pathToDestinationFile);
}
catch
{
    wrdApp.Visible = true;
}