我有一个非常简单的代码来打开一个复制模板excel文件,将一些数据放入其中,然后删除剩余的空行。这适用于大多数模板文件,但只有少数几个,在删除不需要的行后尝试保存文件时,出现异常。
在示例代码中,我省略了数据添加代码,只是保留了删除行功能。当我运行此代码时,如果尝试在1025年后删除行,则会出错。
static void Main(string[] args)
{
try
{
FileInfo fis = new FileInfo(@"D:\ExcelTest\TestFile.xlsx");
FileInfo fi = new FileInfo(Path.Combine(fis.DirectoryName, Guid.NewGuid() + fis.Extension));
fis.CopyTo(fi.FullName);
using (ExcelPackage excelPackage = new ExcelPackage(fi))
{
ExcelWorksheet worksheet = excelPackage.Workbook.Worksheets["C3R"];
int rowstodelete = (171 * 6) - 23;
worksheet.DeleteRow(24, rowstodelete, true);
excelPackage.Save();
}
}
catch (Exception ex)
{
Console.WriteLine(ex.ToString());
}
}
System.InvalidOperationException:保存文件D:\ ExcelTest \ fabf5a3f-714f-4422-a760-73190f34b951.xlsx ---> System.Collections.Generic.KeyNotFoundException:错误:字典中不存在给定密钥。 \ n在System.Collections.Generic.Dictionary`2.get_Item(TKey键)\ r \ n在OfficeOpenXml.ExcelWorksheet.UpdateRowCellData(StreamWriter sw)\ r \ n在OfficeOpenXml.ExcelWorksheet.SaveXml(Stream stream)\ r \ n在OfficeOpenXml.ExcelWorksheet.SaveHandler(ZipOutputStream流,CompressionLevel compressionLevel,字符串文件名)\ r \ n在OfficeOpenXml.Packaging.ZipPackagePart.WriteZip(ZipOutputStream os)\ r \ n在OfficeOpenXml.Packaging.ZipPackage.Save(Stream stream)\ r \ n在OfficeOpenXml.ExcelPackage.Save()\ r \ n ---内部异常堆栈跟踪的结尾--- \ r \ n在OfficeOpenXml.ExcelPackage.Save()\ r \ n在ConsoleApplication1.Program.Main(String [] args)位于C:\ Users \ sm511 \ Documents \ Visual Studio 2015 \ Projects \ ConsoleApplication1 \ Program.cs:line 27