"Index was outside the bounds of the array" 异常 C#

"Index was outside the bounds of the array" exception C#

我正在尝试保存 Excel 工作簿,但是我收到异常 "Index was outside the bounds of the array."

这是代码:

public static void Update()
{

    FileInfo newFile = new FileInfo(@"C:\Users\");

    using (ExcelPackage p = new ExcelPackage(newFile))
    {
        ExcelWorkbook work = p.Workbook;
        ExcelNamedRange sourceRange = work.Names["NewTakt"];
        ExcelNamedRange destinationRange = work.Names["PreviousTakt"];

        ExcelWorksheet worksheet = sourceRange.Worksheet;
        int iRowCount = sourceRange.End.Row - sourceRange.Start.Row + 1;
        int iColCount = sourceRange.End.Column - sourceRange.Start.Column +1;
        for (int iRow = 0; iRow < iRowCount; iRow++)
        {
            for (int iColumn = 0; iColumn < iColCount; iColumn++)
            {               
                worksheet.Cells[destinationRange.Start.Row + iRow, 
                destinationRange.Start.Column + iColumn].Value = 
                worksheet.Cells[sourceRange.Start.Row + iRow, 
                sourceRange.Start.Column + iColumn].Value;
            }
        }

        p.Save();  ---> the exception happens here
    }
}

我做错了什么?非常感谢任何帮助。

在Excel中,单元格和范围不是从0开始,而是从1开始。因此改变循环,从1开始像这样:

    for (int iRow = 1; iRow < iRowCount; iRow++)
    {
        for (int iColumn = 1; iColumn < iColCount; iColumn++)
        {               

行和列在 EPPlus 中的索引为 1,因此您的代码应为:

    for (int iRow = 1; iRow <= iRowCount; iRow++)
    {
        for (int iColumn = 1; iColumn <= iColCount; iColumn++)
        {               
            worksheet.Cells[destinationRange.Start.Row + iRow, 
            destinationRange.Start.Column + iColumn].Value = 
            worksheet.Cells[sourceRange.Start.Row + iRow, 
            sourceRange.Start.Column + iColumn].Value;
        }
    }