我稍微修改了一些来自 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();
}
}
}
}
这是我收到的错误消息:
"Index was outside the bounds of the array."
让我感到困惑的一件事是,当我实例化数组时,我给了它一个 [0] 的索引,那么它是如何超出界限的呢?
最佳答案
您创建了一个仅包含一个元素的数组,该元素将存储在索引 0 处。当然,如果您的内部循环中有多个 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());
}
}
在这两个循环结束时,您将拥有列表中的所有 A 值
allTheSheets
你可以使用另一个 foreach 来查看它的内容。话虽如此,您的代码看起来有点奇怪。用于存储和打印字符串元素的索引始终为零,因此您不应该有任何
Index Out Of Bound
.
关于c# - 在 C# 中创建具有 'foreach' 循环的字符串数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19482735/