C# 尝试将数据从列表复制到二维数组时System.IndexOutOfRangeException

C# 尝试将数据从列表复制到二维数组时System.IndexOutOfRangeException,c#,list,excel-interop,C#,List,Excel Interop,我得到一个例外: System.IndexOutOfRangeException:“索引超出了数组的边界。” 在col++上,当它在第二个循环中时。我正在尝试将值从列表>放到excel列和行中。请让我知道我做错了什么 object[,] cellValuesToWrite = new string[excelRange.Rows.Count, excelRange.Columns.Count]; foreach (List<string> errorR

我得到一个例外:

System.IndexOutOfRangeException:“索引超出了数组的边界。”

在col++上,当它在第二个循环中时。我正在尝试将值从列表>放到excel列和行中。请让我知道我做错了什么

object[,] cellValuesToWrite = new string[excelRange.Rows.Count, excelRange.Columns.Count];                
foreach (List<string> errorRecord in section.ErrorRecords)
{
    int rows = 0;
    int col = 0;
    int length = errorRecord.Count;
    foreach (var elem in errorRecord)
    {
        if (col < length)
        {
            cellValuesToWrite[rows, col] = elem;
            col++;
        }
    }
    rows++;
}

如果使用excelRange.Rows.Count和excelRange.Rows.Count创建数组,则无法访问cellValuesToWrite[5,col],因为索引从0开始,您尝试以这种方式访问第6个元素

为什么不使用好的旧for循环,尤其是在需要索引的情况下:

for (int row = 0; row < cellValuesToWrite.GetLength(0); row++)
{
    for (int col = 0; col < cellValuesToWrite.GetLength(1); col++)
    {
        cellValuesToWrite[row, col] = section.ErrorRecords[row][col];
    }   
}

在每个循环的开始处将行设置为0。增加它没有什么意义。我想在一行中添加一个errorRecord,以此类推。我真的不明白用相同的元素填充每个单元格的意义。但是,如果从单个选定单元格开始,则excelRange.Columns.Count可能为1。您不能调试它吗?不确定,如果excelRange.Columns.Count和errorRecord.Count代表相同数量的列?您应该能够从调试器中获得一些细节。当它抛出异常时,您应该能够看到行、列的值以及cellsToWrite和errorRecord的大小。@SKh欢迎您。尝试使用更多的调试器并逐行遍历代码。您可以自己发现错误: