简体   繁体   English

在C#中使用'foreach'循环创建一个字符串数组

[英]Creating a string array with a 'foreach' loop in C#

I slightly altered some code from msdn.com. 我稍微修改了msdn.com上的一些代码。 I'm trying to get a string array of all the sheet names in an Excel spreadsheet. 我正在尝试在Excel电子表格中获取所有工作表名称的字符串数组。 Can I add some code to the foreach statement so that each time it loops, it places attr.Value into the array? 我可以在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();
            }
        }
    }
}

Here is the error message I'm getting: 这是我收到的错误消息:

"Index was outside the bounds of the array." “指数数组的边界之外。”

One of the things that has me confused is that when I instantiated the array, I gave it an index of [0], so how is that outside the bounds? 令我困惑的一件事是,当我实例化数组时,我给它一个[0]的索引,那么它是如何超出界限的呢?

You have created an array that could contain just one element and this element will be stored at index 0. Of course if you have more than one instance of class A in your inner loop you need more elements in the array. 您已经创建了一个只包含一个元素的数组,并且该元素将存储在索引0中。当然,如果在内部循环中有多个A类实例,则需要在数组中添加更多元素。

Instead of using arrays you could change your code to use a List<string> 您可以更改代码以使用List<string>而不是使用数组

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());
        }
    }

At the end of this two loops you will have all the A values in your list allTheSheets and you can use another foreach to look at its content. 在这两个循环结束时,您将在列表allTheSheets拥有所有A值,并且您可以使用另一个foreach来查看其内容。

Said that, your code looks a bit strange. 说,你的代码看起来有点奇怪。 The index used to store and print the string element is always zero and thus you should not have any Index Out Of Bound . 用于存储和打印字符串元素的索引始终为零,因此您不应该有任何Index Out Of Bound

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

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