2012-03-29 14 views
0

テンプレート文書VS2010を使用して自動化するオフィスのプリントをマージし、マージが正常に動作しますが、保存されたドキュメント(pathToDestinationFile)は2ページとして添付元の文書(pathToTemplate)を持っています。私は、pathToTemplateが単一ページのドキュメントであることを確認しました。 pathToDBとpathToHdrは、マージのデータとして機能するプレーンテキストファイルです。私は間違って何をしていますか?MSWordの自動化は、2007</p> <p>...あまりにも

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(); 
    } 
} 

答えて

0

ソリューションは、ないにしたことは、どんな意味があるかのように、)(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; 
} 
関連する問題