"索引超出了数组的范围"异常C#

时间:2017-09-25 13:10:12

标签: c# asp.net excel epplus epplus-4

我试图保存Excel工作簿但是,我收到了异常"索引超出了数组的范围。"

这是代码:

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
    }
}

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

2 个答案:

答案 0 :(得分:1)

在Excel中,单元格和范围不是从0开始,而是从1开始。因此更改循环,从1开始,如下所示:

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

答案 1 :(得分:1)

行和列在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;
        }
    }