Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

C# Epplus save & saveas error

Tags:

c#

excel

            if (!File.Exists(this.savePath.FullName + "\\" + value + ".xlsx"))
            {
                using ( ExcelPackage exp = new ExcelPackage(finfo))
                {
                    //ExcelPackage exps= new ExcelPackage(pather);
                    ExcelWorksheet exlss = exp.Workbook.Worksheets[timing];
                    exlss.Cells["A1"].LoadFromDataTable(dt, true, TableStyles.Medium9);
                    exp.SaveAs(existing);

                }
            }
            else if (File.Exists(this.savePath.FullName + "\\" + value + ".xlsx")) {
                timing = "2011";
                using (ExcelPackage exp = new ExcelPackage(existing))
                {

                    //ExcelPackage exps= new ExcelPackage(pather);
                    ExcelWorksheet exlss = exp.Workbook.Worksheets[timing];
                    exlss.Cells["A1"].LoadFromDataTable(dt, true, TableStyles.Medium9);
                    exp.Save();

                }
            }

So I am trying to use EPPlus to save to a specific folder thats obtained from the user. However although it saves it just fine in the first using instance, when I try to save or save as it simply throws out an error.

If I use the original file as a template(as I have below) and simply use the first part again it works fine. I have no idea why the save doesnt' work. I've tried to saveAs to a different location but this causes the same error.

If you have any idea please help me.

~edit Here is the error Error saving file C:\Documents and Settings\xxx\Desktop\Testing Andyxxxxxxxx\2481.xlsx

~edit Sorry for all the edits, I'm new to this It's an InvalidOperationException (unhandled)

like image 805
Pradeep Avatar asked Aug 04 '11 18:08

Pradeep


1 Answers

I found the problem, you need to save the file before you try to dispose the worksheet, and in your case you need to ADD a new worksheet before reference it.

like image 169
rasputino Avatar answered Sep 17 '22 23:09

rasputino