2017-04-24 117 views
3

我刪除了一行,並在此行錯誤後合併單元格的地址。 例如,合併單元格爲「A78:C78」。如果我做刪除行中斷合併單元格

worksheet.DeleteRow(5) 

worksheet.Cells[77,1] 

地址爲 「A77」。但是

worksheet.MergedCells[77,1] 

爲空,但它應該是「A77:C77」。

worksheet.Cells[78,1] 

地址爲 「A78」。但是

worksheet.MergedCells[78,1] 

是「A77:C77」,但它應該爲空。 有趣又奇怪的是,* .xlsx文件中存在合併單元格「A77:C77」。 我不明白爲什麼會發生這種情況。 也許有必要在刪除合併單元格的正確地址的行後以某種方式更新工作表?

回答

1

覆蓋此問題的解決方案是在再次獲取合併單元地址之前保存文件,我已經在您提供的同一示例上嘗試了以下代碼,並且package.Save()後的結果似乎是正確的。

using (var package = new ExcelPackage(new System.IO.FileInfo(filePath))) 
     { 
      ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; 
      var address = worksheet.Cells[78, 1];//address is "A78" 
      var mergedadress = worksheet.MergedCells[78, 1];//address is "A78:C78" 
      worksheet.DeleteRow(5); 
      address = worksheet.Cells[77, 1];//address is "A77" 
      mergedaddress = worksheet.MergedCells[77, 1];//null 
      address = worksheet.Cells[78, 1];//address is "A78" 
      mergedaddress = worksheet.MergedCells[78, 1];//address is"A77:C77" 
      package.Save(); 
     } 

using (var package = new ExcelPackage(new System.IO.FileInfo(filePath))) 
     { 
      ExcelWorksheet worksheet = package.Workbook.Worksheets[1]; 
      var address = worksheet.Cells[77, 1];//address is "A77" 
      var mergedaddress = worksheet.MergedCells[77, 1];//Address is "A77:C77" 
      address = worksheet.Cells[78, 1];//address is "A78" 
      mergedaddress = worksheet.MergedCells[78, 1];//null 

      package.Save(); 
     } 

我用EPPLUS v4.1.1.0