Home » excel » Creating a string array with a 'foreach' loop in C#

Creating a string array with a 'foreach' loop in C#

Posted by: admin May 14, 2020 Leave a comment

Questions:

I slightly altered some code from msdn.com. I’m trying to get a string array of all the sheet names in an Excel spreadsheet. Can I add some code to the foreach statement so that each time it loops, it places attr.Value into the array?

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?

How to&Answers:

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.

Instead of using arrays you could change your code to use a 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.

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.