我在使用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
}
答案 0 :(得分:1)
通过检查当前枚举器的类型
来解决它var item = wsEnumerator.Current;
if (item is Excel.Chart)
{
//Do chart operations
}
else if (item is Excel.Worksheet)
{
//Do sheetoperations
}
答案 1 :(得分:0)
您可以重新编写整个代码(无需枚举器):
foreach (dynamic sheet in workBookIn.Sheets)
{
if (sheet is Chart)
// Write your code
else if (sheet is Worksheet)
// Write your code
}