一点背景故事:我有一个小型应用程序,它将使用 Word 根据 Word 模板和公司活动目录中的数据生成 Outlook 签名。它在装有 Office 2007 的计算机上运行良好,因为我在自己的计算机上编码时使用了“Microsoft Word 12.0 对象库”。
不过,网络上有不少安装了 Office 2003 的计算机,并且在这些计算机上缺少“Microsoft Word 12.0 对象库”,导致左右出现异常。
我的问题是:如何检测安装了哪个版本的 Office,从而检测到哪个版本的“Microsoft Word 对象库”可用,然后加载它。我很确定我正在使用的功能在“Microsoft Word 12.0 对象库”和“Microsoft Word 11.0 对象库”中。
如果有人感兴趣,这是我当前用于生成签名的代码:
class Signature
{
public Dictionary<string, string> TemplateMappings { get; set;}
public string SignatureTemplateFileName { get; set; }
public string SignatureName { get; set;}
public bool UseSignatureWithNewMessages { get; set; }
public bool UseSignatureInReplyMessages { get; set; }
public Signature()
{
UseSignatureWithNewMessages = true;
UseSignatureInReplyMessages = true;
TemplateMappings = new Dictionary<string, string>();
}
public void Create()
{
if(string.IsNullOrEmpty(SignatureTemplateFileName) || !File.Exists(SignatureTemplateFileName))
{
throw new InvalidOperationException("SignatureTemplateFileName is null or the file do not exists");
}
if(string.IsNullOrEmpty(SignatureName))
{
throw new InvalidOperationException("No SignatureName specified");
}
object nullObject = System.Reflection.Missing.Value;
object signatureTemplate = SignatureTemplateFileName;
// open word doc
var word = new ApplicationClass();
var doc = word.Documents.Add(ref signatureTemplate, ref nullObject, ref nullObject, ref nullObject);
// search/replace user info
object wdReplaceAll = WdReplace.wdReplaceAll;
var find = word.Selection.Find;
foreach (var pair in TemplateMappings)
{
find.Text = pair.Key;
find.Forward = true;
find.MatchCase = true;
find.MatchWholeWord = true;
find.Replacement.Text = pair.Value;
find.Execute(ref nullObject /* FindText */,
ref nullObject /* MatchCase*/,
ref nullObject /* MatchWholeWord*/,
ref nullObject /* MatchWildcards*/,
ref nullObject /* MatchSoundsLike*/,
ref nullObject /* MatchAllWordForms*/,
ref nullObject /* Forward*/,
ref nullObject /* Wrap*/,
ref nullObject /* Format*/,
ref nullObject /* ReplaceWith*/,
ref wdReplaceAll /* Replace*/,
ref nullObject /* MatchKashida*/,
ref nullObject /* MatchDiacritics*/,
ref nullObject /* MatchAlefHamza*/,
ref nullObject /* MatchControl */);
}
// Add signature to outlook
var signatureRange = doc.Range(ref nullObject, ref nullObject);
word.EmailOptions.EmailSignature.EmailSignatureEntries.Add(SignatureName, signatureRange);
// set new signature as default for news messages and replies
if (UseSignatureWithNewMessages)
word.EmailOptions.EmailSignature.NewMessageSignature = SignatureName;
if (UseSignatureInReplyMessages)
word.EmailOptions.EmailSignature.ReplyMessageSignature = SignatureName;
// close and clean up
doc.Saved = true;
doc.Close(ref nullObject, ref nullObject, ref nullObject);
word.Quit(ref nullObject, ref nullObject, ref nullObject);
}
}
任何帮助都感激不尽。也欢迎输入上面的代码;我没有任何针对 Office 互操作库进行编码的经验,因此我确信我可以做一些不同的事情。
最好的问候,埃吉尔。