簡體   English   中英

郵件合並Word 2003標頭字段C#

[英]Mail Merge Word 2003 Header Fields C#

我正在編寫一個小型庫,該庫將對C#中的Word 2003 .DOT文檔執行MailMerge。 我能夠像這樣檢索和替換所有文檔主體字段:

foreach (Field mergeField in document.Fields)
    {
       if (mergeField.Type == WdFieldType.wdFieldMergeField)
       {
          string fieldText = mergeField.Code.Text;
          string fieldName = Extensions.GetFieldName(fieldText);

          if (values.ContainsKey(fieldName))
          {
             mergeField.Select();
             application.Selection.TypeText(values[fieldName]);
          }
       }
    }

但這不會從文檔中檢索“頁眉”或“頁腳”字段。

我已經試過了:

   subscriptionDocument.Sections[1].Headers[WdHeaderFooterIndex.wdHeaderFooterPrimary].Range.Fields.Count;

用於查詢標題字段,但是即使字段實際存在,計數仍返回“ 0”。

有沒有一種方法可以對頁眉和頁腳字段產生理想的影響?

您的代碼是正確的,通常您可以使用它來計數標頭中的字段。 我猜您正在使用的測試文檔的布局略有不同,例如標題或首頁標題。 如果在“ wdHeaderFooterPrimary”部分中激活了“不同的第一頁”,則您不能訪問第一頁。 在Word中打開測試文檔,啟動VBA編輯器(Alt + F11),轉到“即時Windows”並鍵入

?activedocument.Sections(1).Headers(wdHeaderFooterFirstPage).Range.Fields.Count

訪問第一頁標題中的字段。

您需要與主文檔分開顯式搜索頁眉和頁腳。 這對我有用...

putField("First_Name", "Fred");
putField("Last_Name", "Bloggs");

private void putField(string search, string replace) {
    foreach (Section section in doc.Sections) {
        doReplace(section.Range.Find, search, replace);
    foreach (HeaderFooter h in section.Headers) {
        doReplace(h.Range.Find, search, replace);
    }
     foreach (HeaderFooter f in section.Footers) {
        doReplace(f.Range.Find, search, replace);
    }
    }
}

private void doReplace(Find fnd, string search, string replace){
        fnd.ClearFormatting();
        fnd.Replacement.ClearFormatting();
        fnd.Forward = true;
        fnd.Wrap = WdFindWrap.wdFindContinue;
        fnd.Text = "«" + search + "»";
        fnd.Replacement.Text = replace;
        fnd.Execute(Replace: WdReplace.wdReplaceAll);
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM