MailMerge期间不保留文档格式

时间:2013-09-19 19:15:34

标签: c# ms-word mailmerge

我正在尝试自动化MailMerge,并设法让它几乎完成。我可以制作单独的文档并合并它们。问题是在“InsertFile”调用期间,文档被重新格式化,并且它会破坏文档。因为文件是一个字母,并且地址信息必须在同一个地方打印,所以我一直坚持,直到我能够纠正格式。我正在使用的功能如下。如果有人能指出我正确的方向,我将不胜感激。在搜索的一天,我无法在网上找到任何东西。

    public bool mailMergeWithTemplate(string strTemplatePath, string strDestinationPath, DataSet dsData, out string strError)
    {
        strError = "";
        object objMissing = Missing.Value; //null value
        object objTrue = true;
        object objFalse = false;
        object objTemplatePath = strTemplatePath;
        object objOutputPath = strDestinationPath;
        object objOutputPathTemp = strDestinationPath.Substring(0, strDestinationPath.IndexOf(".docx")) + "_temp.docx";
        object sectionStart = WdSectionStart.wdSectionNewPage;

        Application objWord = null;

        try
        {
            objWord = new Application { Visible = true };

            //create an empty document into which we will insert all the merge docs
            var objFinalWordDoc = objWord.Documents.Add(ref objMissing, ref objMissing, ref objMissing, ref objMissing);

            //for each record in the dataset
            var count = 1;

            foreach (DataRow dr in dsData.Tables[0].Rows)
            {
                //insert a document for each record
                var objWordDoc = objWord.Documents.Add(ref objTemplatePath, ref objMissing, ref objMissing, ref objMissing);
                if (objWordDoc.Fields.Count == 0)
                    return false;

                objWordDoc.Activate();

                // Perform mail merge of each field
                foreach (Field myMergeField in objWordDoc.Fields)
                {
                    var rngFieldCode = myMergeField.Code;
                    var strFieldText = rngFieldCode.Text;

                    // ONLY GET THE MAILMERGE FIELDS
                    if (!strFieldText.StartsWith(" MERGEFIELD")) continue;

                    var strFieldName = string.Empty;

                    if (!strFieldText.Contains("Account"))
                    {
                        var intEndMerge = strFieldText.IndexOf("\\");
                        strFieldName = strFieldText.Substring(11, intEndMerge - 11);
                    }
                    else
                        strFieldName = "Account";

                    strFieldName = strFieldName.Trim().Replace("\"", "");

                    //find a matching dataset column
                    foreach (DataColumn col in dsData.Tables[0].Columns)
                    {
                        var strKey = col.ColumnName;
                        var strValue = dr[strKey].ToString();

                        if (strFieldName != strKey) continue;

                        myMergeField.Select();
                        objWord.Selection.TypeText(strValue);
                    }
                }
                //SAVE THE DOCUMENT as temp
                objWordDoc.SaveAs(ref objOutputPathTemp, ref objMissing, ref objMissing, ref objMissing,
                                    ref objMissing, ref objMissing, ref objMissing, ref objMissing,
                                    ref objMissing, ref objMissing, ref objMissing, ref objMissing,
                                    ref objMissing, ref objMissing, ref objMissing, ref objMissing);

                //CLOSE THE DOCUMENT
                objWordDoc.Close(ref objFalse, ref objMissing, ref objMissing);
                Marshal.ReleaseComObject(objWordDoc);
                objWordDoc = null;

                //NOW ADD THE NEW DOC TO THE MAIN DOC
                objFinalWordDoc.Activate();
                objWord.Selection.InsertFile(objOutputPathTemp.ToString(),
                                                ref objMissing, ref objMissing, ref objMissing, ref objMissing);

                if(count < dsData.Tables[0].Rows.Count)
                    objWord.Selection.InsertBreak(ref sectionStart);

                count++;
            }

            //SAVE THE FINAL DOC
            objFinalWordDoc.SaveAs(ref objOutputPath, ref objMissing, ref objMissing, ref objMissing,
                                    ref objMissing, ref objMissing, ref objMissing, ref objMissing,
                                    ref objMissing, ref objMissing, ref objMissing, ref objMissing,
                                    ref objMissing, ref objMissing, ref objMissing, ref objMissing);

            //CLOSE THE FINAL DOC
            objFinalWordDoc.Close(ref objFalse, ref objMissing, ref objMissing);
            Marshal.ReleaseComObject(objFinalWordDoc);
            objFinalWordDoc = null;

            //now delete the temp file
            File.Delete(objOutputPathTemp.ToString());

            return true;
        }
        catch (Exception ex)
        {
            strError = ex.Message;
        }
        finally
        {
            //RELEASE WORD ITSELF
            if (objWord != null)
            {
                objWord.Quit(ref objMissing, ref objMissing, ref objMissing);
                Marshal.ReleaseComObject(objWord);
            }
            objWord = null;

            GC.Collect();
        }

        return false;
    }

问题出现在这里:

objWord.Selection.InsertFile(objOutputPathTemp.ToString(),
                                                ref objMissing, ref objMissing, ref objMissing, ref objMissing);

那么有没有人想过如何纠正这个问题呢?

1 个答案:

答案 0 :(得分:0)

假设您可以控制插入文件的内容,

  • 确保插入的文件没有分节符。
  • 选择插入文件的全部内容,但最终内容除外 段落标记(“带有”部分/文档格式 信息)。假设您将书签称为“theContent”
  • 将“theContent”指定为“Range”参数(即第2个 insertFile调用的参数)