0

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.

René Vogt
  • 43,056
  • 14
  • 77
  • 99
coffeetime
  • 121
  • 2
  • 6
  • 14
  • 4
    Do you know how to debug? Debug step by step until you find what state is causing the error. – hellogoodnight Sep 25 '17 at 13:13
  • 5
    I'm willing to bet the exception isn't on the line you think it is. – DavidG Sep 25 '17 at 13:14
  • Possible duplicate of [What is an IndexOutOfRangeException / ArgumentOutOfRangeException and how do I fix it?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-i-f) – VDWWD Sep 25 '17 at 14:11

2 Answers2

2

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++)
        {               
Vityata
  • 42,633
  • 8
  • 55
  • 100
1

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;
        }
    }
Pete
  • 1,807
  • 1
  • 16
  • 32