简体   繁体   English

Excel Interop,用于工作表和图表的迭代工作簿

[英]Excel Interop, iterating workbook for worksheet and chart

I have a scenario while working with Microsoft Excel Interop. 我在使用Microsoft Excel Interop时遇到了一个情况。

System.Collections.IEnumerator wsEnumerator = excelApp.ActiveWorkbook.Worksheets.GetEnumerator();
while (wsEnumerator.MoveNext())
{
    wsCurrent = (Excel.Worksheet)wsEnumerator.Current;
    //Worksheet operation Follows   
}

I am operating on Worksheets, so i can not have Chart in this. 我在工作表上进行操作,因此无法在其中使用图表。 What i want to do achieve is operate on Sheets and check if it is a Worksheet or Chart, and act accordingly. 我要实现的是在工作表上进行操作,并检查它是工作表还是图表,并采取相应的措施。

As sheets contain both Worksheet, Chart and "Excel 4.0 Macro", so what is the type of Sheets each entry as it can hold any of the type mentioned. 由于工作表既包含工作表,图表又包含“ Excel 4.0宏”,因此每个条目的工作表类型是什么,因为它可以容纳上述任何类型。

System.Collections.IEnumerator wsEnumerator = workBookIn.Sheets.GetEnumerator();
while (wsEnumerator.MoveNext())
{
    //Identify if its a chart or worksheet
}

Solved it by checking type of Current Enumerator 通过检查当前枚举器的类型来解决

var item = wsEnumerator.Current;                   
if (item is Excel.Chart)
{
    //Do chart operations
}
else if (item is Excel.Worksheet)
{
    //Do sheetoperations
}

You can re-write the entire code (without enumerator): 您可以重写整个代码(不带枚举器):

foreach (dynamic sheet in workBookIn.Sheets)
{
    if (sheet is Chart)
        // Write your code
    else if (sheet is Worksheet)
        // Write your code
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM