coffeetime
coffeetime

Reputation: 131

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

I'm trying to save the Excel workbook however, I'm receiving the exception "Index was outside the bounds of the array."

This is the code:

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

What am I doing wrong? Any help is greatly appreciated it.

Upvotes: 0

Views: 1774

Answers (2)

Pete
Pete

Reputation: 1867

Rows and Columns are 1-indexed in EPPlus, so your code should be:

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

Upvotes: 1

Vityata
Vityata

Reputation: 43595

In Excel, cells and ranges do not start from 0, but from 1. Thus change the loops, starting from 1 like this:

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

Upvotes: 2

Related Questions