我在使用Microsoft Excel Interop时有一个场景。
System.Collections.IEnumerator wsEnumerator = excelApp.ActiveWorkbook.Worksheets.GetEnumerator();
while (wsEnumerator.MoveNext())
{
wsCurrent = (Excel.Worksheet)wsEnumerator.Current;
//Worksheet operation Follows
}
我在Worksheets上运行,所以我不能在这里使用Chart。我想要实现的是在Sheets上操作并检查它是否是工作表或图表,并采取相应的行动。
由于工作表包含工作表,图表和“Excel 4.0宏”,因此每个条目的表格类型是什么,因为它可以包含任何提到的类型。
System.Collections.IEnumerator wsEnumerator = workBookIn.Sheets.GetEnumerator();
while (wsEnumerator.MoveNext())
{
//Identify if its a chart or worksheet
}
通过检查Current Enumerator的类型来解决它
var item = wsEnumerator.Current;
if (item is Excel.Chart)
{
//Do chart operations
}
else if (item is Excel.Worksheet)
{
//Do sheetoperations
}
您可以重写整个代码(没有枚举器):
foreach (dynamic sheet in workBookIn.Sheets)
{
if (sheet is Chart)
// Write your code
else if (sheet is Worksheet)
// Write your code
}