首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >使用mergefield的Microsoft if语句无法工作。

使用mergefield的Microsoft if语句无法工作。
EN

Stack Overflow用户
提问于 2014-11-28 10:38:57
回答 1查看 1.5K关注 0票数 2

我试图用microsoft (Microsoft.Office.Interop.Word dll)和c#实现IF语句。我有一个模板如下-

我会得到这样的结果-

我的代码是这样的

代码语言:javascript
复制
 Dictionary<String, String> valueDic = new Dictionary<string, string>();
 valueDic.Add("Gender", "Male");
 Object oMissing = System.Reflection.Missing.Value;
 Object oTemplatePath = @"E:\\ContactTemplate2.docx";
 Application wordApp = new Application();
 Document wordDoc = new Document();
 wordDoc = wordApp.Documents.Add(ref oTemplatePath, ref oMissing, ref oMissing, ref oMissing);
 foreach (Field myMergeField in wordDoc.Fields)
 {
   Range rngFieldCode = myMergeField.Code;
   String fieldText = rngFieldCode.Text;
   if (fieldText.StartsWith(" MERGEFIELD"))
   {
     Int32 endMerge = fieldText.IndexOf("\\");
     Int32 fieldNameLength = fieldText.Length - endMerge;
     String fieldName = fieldText.Substring(11, endMerge - 11);
     fieldName = fieldName.Trim();
     if (valueDic.ContainsKey(fieldName))
     {
       myMergeField.Select();
       wordDoc.Application.Selection.TypeText(valueDic[fieldName]);
     }
     else
     {
       myMergeField.Select();
       wordDoc.Application.Selection.TypeText(" ");
     }
   }
 }
 wordDoc.SaveAs(@"E:\\myfile.docx");
 wordApp.Application.Quit();

我想要结果就像-

有人能帮我解决问题吗?

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2014-11-29 13:26:54

因此,如果MERGEFIELD字段名在您的valueDic列表中,您想用它的名称替换mergefield吗?

如果是这样,我建议您接下来需要的是这样的东西(您可能需要更正语法)。

代码语言:javascript
复制
if (valueDic.ContainsKey(fieldname))
{
  Range rngFieldResult = myMergeField.Result;
  myMergeField.Unlink();
  Range.Text = valueDic[fieldName];
}

如果删除集合的成员,还需要验证字段迭代是否仍然有效。如果不是,您可能需要使用计数器向后迭代。您还可能需要注意您正在使用的任何一个范围的IncludeFieldCodes和IncludeHiddenText属性TextRetrievalMode。

(注:如果你这样做,单词将把{ If Male = "Male“}解释为”男性“和”男性“之间的字符串比较,除非有一个书签名为”男性“,在这种情况下,它会比较书签值和”男性“)

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/27186878

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档