C# 使用';foreach&x27;循环(C)#

C# 使用';foreach&x27;循环(C)#,c#,arrays,excel,openxml-sdk,C#,Arrays,Excel,Openxml Sdk,我稍微修改了msdn.com上的一些代码。我正在尝试获取Excel电子表格中所有工作表名称的字符串数组。我是否可以在foreach语句中添加一些代码,以便每次循环时都将attr.Value放入数组 public static void GetSpreadsheetData(string fileName) { using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(fileName, false)

我稍微修改了msdn.com上的一些代码。我正在尝试获取Excel电子表格中所有工作表名称的字符串数组。我是否可以在
foreach
语句中添加一些代码,以便每次循环时都将attr.Value放入数组

public static void GetSpreadsheetData(string fileName)
{
    using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(fileName, false))
    {
        string[] allTheSheets = new string[0];
        string[] allTheData = new string[0];
        S sheets = spreadsheetDocument.WorkbookPart.Workbook.Sheets;

        foreach (E sheet in sheets)
        {
            foreach (A attr in sheet.GetAttributes())
            {
                int i = 0;
                string sheetName = attr.Value;
                allTheSheets[i] = attr.Value.ToString();
                i++;
                Console.WriteLine(allTheSheets[0]);
                Console.ReadLine();
            }
        }
    }
}
下面是我收到的错误消息:

“索引超出了数组的边界。”


让我感到困惑的一点是,当我实例化数组时,我给了它一个索引[0],那么这怎么会超出范围呢?

您创建了一个数组,它可以只包含一个元素,而这个元素将存储在索引0处。当然,如果在内部循环中有多个类A实例,那么数组中需要更多元素

不使用数组,您可以将代码更改为使用
列表

使用(SpreadsheetDocument SpreadsheetDocument=SpreadsheetDocument.Open(文件名,false))
{
列出所有表=新列表();
列出所有数据=新列表();
S sheets=电子表格Document.WorkbookPart.Workbook.sheets;
foreach(以页为单位的E页)
{
foreach(sheet.GetAttributes()中的属性)
{
字符串sheetName=attr.Value;
Add(attr.Value.ToString());
}
}
在这两个循环的末尾,您的列表中将有所有的A值
所有的表
,您可以使用另一个foreach查看其内容


话虽如此,您的代码看起来有点奇怪。用于存储和打印字符串元素的索引始终为零,因此您在创建数组(所有表)时不应该有任何
索引超出范围使用
0
长度。您考虑过使用列表吗?数组的大小是固定的。您无法调整它的大小。因此,您首先必须正确调整它的大小。如果您不知道大小,请使用
列表
代替。您的代码有点奇怪。您知道在哪一行出现异常。仔细查看,您在数组中有一个索引t总是为零,这会使你的数组变得无用。@L.B是的!这似乎很有效!!!这里相对较新,有没有升级投票或我可以给你的东西?@Steve我的代码很奇怪,因为我几乎不知道我在做什么,哈哈。非常感谢。尝试了列表,它似乎工作得很好!我感谢你的帮助。
using (SpreadsheetDocument spreadsheetDocument = SpreadsheetDocument.Open(fileName, false))
{
    List<string> allTheSheets = new List<string>();
    List<string> allTheData = new List<string>();
    S sheets = spreadsheetDocument.WorkbookPart.Workbook.Sheets;


    foreach (E sheet in sheets)
    {
        foreach (A attr in sheet.GetAttributes())
        {
            string sheetName = attr.Value;
            allTheSheets.Add(attr.Value.ToString());
        }
    }