我开发了一个使用Microsoft.Office.Interop.Word参考版本14的dll。我机器上安装的Word版本是2010.
当我在具有Word 2007或2003版本的其他计算机上安装我的dll时,出现以下错误:
Could not load file or assembly 'Microsoft.Office.Interop.Word version=14.0.0
我发现here设置'嵌入互操作类型'引用'True'可以解决问题,但是当我这样做时,当我使用Microsoft.Office.Interop.Word.ApplicationClass时出现错误代码;
Interop type 'Microsoft.Office.Interop.Word.ApplicationClass' cannot be embedded
如果要在使用以前Word版本的计算机上安装dll,我应该怎么做?
答案 0 :(得分:1)
我将在这里给出一个使用后期绑定单词的工作示例。它是在不久前制作的,可能值得用dynamic
重写:
// try to open word
Type typeWordApplication = Type.GetTypeFromProgID("Word.Application");
if (typeWordApplication == null)
throw new Exception("Word is not installed (Word.Application is not found)");
object objWordApplication = Activator.CreateInstance(typeWordApplication);
object objDocuments = objWordApplication.GetType().InvokeMember("Documents", BindingFlags.GetProperty, null, objWordApplication, null);
object[] param = new object[] { Missing.Value, Missing.Value, Missing.Value, Missing.Value };
object objDocument = objDocuments.GetType().InvokeMember("Add", BindingFlags.InvokeMethod, null, objDocuments, param);
object start = 0;
object end = 0;
object objRange = objDocument.GetType().InvokeMember("Range", BindingFlags.InvokeMethod, null, objDocument, new object[] { start, end });
// set text
objRange.GetType().InvokeMember("Text", BindingFlags.SetProperty, null, objRange, new object[] { text });
// set font
object objFont = objRange.GetType().InvokeMember("Font", BindingFlags.GetProperty, null, objRange, null);
objFont.GetType().InvokeMember("Name", BindingFlags.SetProperty, null, objFont, new object[] { "Courier" });
objFont.GetType().InvokeMember("Size", BindingFlags.SetProperty, null, objFont, new object[] { (float)8 });
start = objRange.GetType().InvokeMember("End", BindingFlags.GetProperty, null, objRange, null);
end = start;
objRange = objDocument.GetType().InvokeMember("Range", BindingFlags.InvokeMethod, null, objDocument, new object[] { start, end });
// select text
objRange.GetType().InvokeMember("Select", BindingFlags.InvokeMethod, null, objRange, null);
objWordApplication.GetType().InvokeMember("Visible", BindingFlags.SetProperty, null, objWordApplication, new object[] { true });
Marshal.ReleaseComObject(objWordApplication);
它的优点:
GetTypeFromProgID
失败 - 您只需要求用户安装内容)。缺点:
dynamic
);