为什么不能从Excel interop中设置一个对象? [英] Why can't set cast an object from Excel interop?

查看:212
本文介绍了为什么不能从Excel interop中设置一个对象?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

尝试获取工作表的引用(使用Excel interop):

Trying to get a reference to the worksheets (using Excel interop):

Excel.Application xl = new Excel.ApplicationClass();
Excel.Workbooks xlWorkBooks = xl.Workbooks;
Excel.Workbook xlWorkBook = xlWorkBooks.Open(fileName, 0, false, 5, "", 
                      "", true, Excel.XlPlatform.xlWindows, "\t",
                      false, false, 0, true, 1, 0);

// Next line crashes
Excel.Worksheets xlWorkSheets = (Excel.Worksheets) xlWorkBook.Worksheets; 

错误是它无法投射:


无法将类型为System .__ ComObject的COM对象转换为接口类型Microsoft.Office.Interop.Excel.Worksheets。此操作失败,因为由于以下错误,IID'{000208B1-0000-0000-C000-000000000046}接口的COM组件上的QueryInterface调用失败:不支持此类接口(HRESULT异常:0x80004002(E_NOINTERFACE))

Unable to cast COM object of type 'System.__ComObject' to interface type 'Microsoft.Office.Interop.Excel.Worksheets'. This operation failed because the QueryInterface call on the COM component for the interface with IID '{000208B1-0000-0000-C000-000000000046}' failed due to the following error: No such interface supported (Exception from HRESULT: 0x80004002 (E_NOINTERFACE)).

我的演员是否不正确?

推荐答案

是的,你的演员错了。

_Workbook.Sheets 给你一个表格实例。此界面为您提供所有类型的工作表,而不仅仅是工作表;主要包括图表,宏表等。

_Workbook.Sheets gives you a Sheets instance. This interface gives you all types of sheets, not just worksheets; mainly, it includes charts, macro sheets, etc.

另一方面,工作表界面仅给出工作表 - 而不是图表。

On the other hand, the Worksheets interface only gives you worksheets - not charts.

接口不能彼此分配;因此,您会收到COM错误。这是令人困惑的 - 我甚至不确定是否可以通过PIA获得 Worksheets 接口的实例 - 但是这是Office的Office Interop for ya。

The interfaces are not assignable to each other; therefore, you get the COM error. It's confusing - I'm not even sure if it's possible to get an instance of the Worksheets interface through the PIA - but that's Office Interop for ya.

只要您使用 _Workbook.Worksheets 属性,而不是 _Workbook.Sheets 属性,你应该得到一个 Sheets 的实例,它只返回 Worksheet 对象 - 尽管接口有能力提供其他类型的床单。

As long as you use the _Workbook.Worksheets property instead of the _Workbook.Sheets property, you should get an instance of Sheets that only returns Worksheet objects - in spite of the fact that the interface is capable of providing other types of sheets.

这篇关于为什么不能从Excel interop中设置一个对象?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆