1
Vote

using Drawings.Remove("Picturename"); messes up worksheet object after all drawings are removed

description

I have a template sheet "template".template has 3 pictures.
I remove all drawings,then clone template as new sheet but deleting template fails.
Code:
string template_path="some path..of xlsx file"
System.IO.FileInfo fileinfo = new System.IO.FileInfo(template_path);
using(ExcelPackage package=new ExcelPackage(fileinfo)){
ExcelWorkbook workbook = package.Workbook;
ExcelWorksheet sheet = workbook.Worksheets["template"];
sheet.Cells["AB2"].Value=100;
sheet.Drawings.Remove("Picture1");
sheet.Drawings.Remove("Picture2");
sheet.Drawings.Remove("Picture3");
workbook.Worksheets["template"].Calculate();
workbook.Worksheets.Add("result",sheet);//clone sheet
workbook.Worksheets.MoveBefore("result","template");//move result before template
try{
package.Workbook.Worksheets.Delete(workbook.Worksheets["template"]);//delete template
}
catch(Exception e){Console.WriteLine(e.Message);}//throws message: "the given key was not present in the dictionary"
//..do something else with template file
//
System.IO.FileInfo fileinfo2 = new System.IO.FileInfo("asdasdas\folder\done.xlsx");
package.SaveAs(fileinfo2);
}//end using

//###
As a workaround I put another dummy white square picture as "Picture4" and the code works. It seems something goes wrong when all Drawings in the worksheet is deleted.

comments