简体   繁体   English

从Excel工作簿删除工作表时出错

[英]Error while deleting worksheet from a Excel workbook

I need to delete some sheets from an Excel workbook in C#. 我需要从C#中的Excel工作簿中删除一些工作表。

But, my code does not work. 但是,我的代码不起作用。

    // **aDeleteList** hold the sheets that need to be deleted from the workbook wbk
    static void delete_sht(ref MsExcel.Workbook wbk, List<string> aDeleteList)
    {
        MsExcel.Sheets my_st = wbk.Sheets;
        foreach (MsExcel.Worksheet s in my_st)
        {
            if (aDeleteList.Contains(s.Name))
                s.Delete();
            int t1 = my_st.Count;
            int t = wbk.Sheets.Count;
        }
    }

The values of t and t1 do not change no matter t和t1的值不会改变

          s.Delete()

has been executed. 已执行。

Any help would be appreciated. 任何帮助,将不胜感激。

Removing while iterating can be a bit tricky. 在迭代时删除可能会有些棘手。 You are iterating through s and trying to delete s also. 您正在遍历s并尝试删除s。 Something like this should work a bit better 这样的事情应该会更好一些

static void delete_sht(ref MsExcel.Workbook wbk, List<string> aDeleteList)
    {
        MsExcel.Sheets my_st = wbk.Sheets;

        for (int i = my_st.Count - 1; i >= 0; --i)
            if (aDeleteList.Contains(my_st[i].Name))
                my_st.RemoveAt(i);
    }

You cannot delete from an underlying collection while iterating in foreach . foreach进行迭代时,不能从基础集合中删除。 Use a for loop instead. 请使用for循环。
From MSDN : 从MSDN:

The foreach statement repeats a group of embedded statements for each element in an array or an object collection that implements the System.Collections.IEnumerable or System.Collections.Generic.IEnumerable interface. foreach语句对实现System.Collections.IEnumerable或System.Collections.Generic.IEnumerable接口的数组或对象集合中的每个元素重复一组嵌入式语句。 The foreach statement is used to iterate through the collection to get the information that you want, but can not be used to add or remove items from the source collection to avoid unpredictable side effects . foreach语句用于遍历集合以获取所需的信息, 但不能用于在源集合中添加或删除项,以避免不可预期的副作用 If you need to add or remove items from the source collection, use a for loop. 如果需要在源集合中添加或删除项目,请使用for循环。

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

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