如何将 COM 对象类型转换为 Excel.Checkbox 类型
我正在向 Excel 添加一个复选框,但在将“System.__ComObject”类型的 COM 对象转换为接口类型“Microsoft.Office.Interop.Excel.CheckBox”时遇到问题,任何帮助将不胜感激!我正在使用 Visual Studio 2008 和 Office 2007 开发 Web 应用程序。错误发生在这一行:- chkBx = (Microsoft.Office.Interop.Excel.CheckBox)obj;
Microsoft.Office.Interop.Excel.OLEObjects objs = (Microsoft.Office.Interop.Excel.OLEObjects)mWSheet1.OLEObjects(System.Reflection.Missing.Value);
Microsoft.Office.Interop.Excel.OLEObject obj = objs.Add("Forms.CheckBox.1",
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
false,
false,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
234,
234,
108,
21);
Microsoft.Office.Interop.Excel.CheckBox chkBx;
chkBx = (Microsoft.Office.Interop.Excel.CheckBox)obj;
chkBx.Value = true;
chkBx.Caption = "xyz";
I am adding a checkbox to excel and i have issue casting a COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Excel.CheckBox', any help would be appreciated! I am working on web app using visual studio 2008 and office 2007. The error happens at this line :- chkBx = (Microsoft.Office.Interop.Excel.CheckBox)obj;
Microsoft.Office.Interop.Excel.OLEObjects objs = (Microsoft.Office.Interop.Excel.OLEObjects)mWSheet1.OLEObjects(System.Reflection.Missing.Value);
Microsoft.Office.Interop.Excel.OLEObject obj = objs.Add("Forms.CheckBox.1",
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
false,
false,
System.Reflection.Missing.Value,
System.Reflection.Missing.Value,
234,
234,
108,
21);
Microsoft.Office.Interop.Excel.CheckBox chkBx;
chkBx = (Microsoft.Office.Interop.Excel.CheckBox)obj;
chkBx.Value = true;
chkBx.Caption = "xyz";
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
在我看来,你无法投射它,因为它根本没有实现该接口。您可以使用
as
运算符检查System.__ComObject
是否支持不进行强制转换的接口,从而引发异常,如下所述:如何:使用 Visual C# .NET 检查 COM 对象 (System.__ComObject) 的类型。我想知道您是否使用了错误的方法将复选框添加到工作表中。不是更常见的方法是通过 <代码>Microsoft.Office.Tools.Excel.ControlCollection,如下所述:在运行时向 Office 文档添加控件。
如果您使用
ControlCollection
,我认为您的代码最终会看起来像这样:It looks to me like you can't cast it because it simply doesn't implement that interface. You can check if a
System.__ComObject
supports an interface without casting, and consequently throwing an exception, by using theas
operator as described here: HOW TO: Check the Type of a COM Object (System.__ComObject) with Visual C# .NET.I wonder if you are using the wrong method to add the checkbox to a worksheet. Isn't the more common method to go through
Microsoft.Office.Tools.Excel.ControlCollection
as described here: Adding Controls to Office Documents at Run Time.If you used
ControlCollection
, I think your code would end up looking something like this: