2017-09-25 71 views
0

我試圖保存Excel工作簿,但是,我收到異常「索引超出了數組的範圍」。「索引超出了數組範圍」異常C#

這是代碼:

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

我在做什麼錯?任何幫助非常感謝它。

+4

你知道如何調試嗎?一步一步調試,直到找到導致錯誤的狀態。 – hellogoodnight

+5

我敢打賭,這個例外不在你認爲的範圍內。 – DavidG

+0

可能的重複[什麼是IndexOutOfRangeException/ArgumentOutOfRangeException,以及如何解決它?](https://stackoverflow.com/questions/20940979/what-is-an-indexoutofrangeexception-argumentoutofrangeexception-and-how-do-if) – VDWWD

回答

1

在Excel中,細胞和範圍不從0開始的,而是從1這樣改變的循環,從1開始是這樣的:在EPPlus

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

非常感謝! – coffeetime

1

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

謝謝皮特! – coffeetime

+0

不客氣! – Pete