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



我正在尝试保存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
    }
}

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

在excel,单元格和范围中不是从0开始,而是从1开始。因此,从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;
        }
    }

相关内容

  • 没有找到相关文章

最新更新