I'm trying to create an Excel file using EPPLUS in a controller of an MVC application.
The file appears to be getting created just fine, but chokes when I try to save:
[HttpPost]
public FileResult getBill(int billMonth, int billYear)
{
FileInfo newFile = new FileInfo("C:\\cool.xlsx");
if (newFile.Exists)
{
newFile.Delete(); // ensures we create a new workbook
newFile = new FileInfo("cool.xlsx");
}
using (ExcelPackage package = new ExcelPackage(newFile))
{
// add a new worksheet to the empty workbook
ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Inventory");
//Add the headers
worksheet.Cells[1, 1].Value = "ID";
...
// save our new workbook and we are done!
package.Save();
}
The error I am getting: Error saving file C:\cool.xlsx
System.InvalidOperationException was unhandled by user code
HResult=-2146233079
Message=Error saving file C:\cool.xlsx
Source=EPPlus
StackTrace:
at OfficeOpenXml.ExcelPackage.Save()
at ...BillingController.getBill(Int32 billMonth, Int32 billYear) in ...\Controllers\BillingController.cs:line 118
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ReflectedActionDescriptor.Execute(ControllerContext controllerContext, IDictionary`2 parameters)
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethod(ControllerContext controllerContext, ActionDescriptor actionDescriptor, IDictionary`2 parameters)
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass37.<>c__DisplayClass39.<BeginInvokeActionMethodWithFilters>b__33()
at System.Web.Mvc.Async.AsyncControllerActionInvoker.<>c__DisplayClass4f.<InvokeActionMethodFilterAsynchronously>b__49()
InnerException: System.UnauthorizedAccessException
HResult=-2147024891
Message=Access to the path 'C:\cool.xlsx' is denied.
Source=mscorlib
StackTrace:
at System.IO.__Error.WinIOError(Int32 errorCode, String maybeFullPath)
at System.IO.FileStream.Init(String path, FileMode mode, FileAccess access, Int32 rights, Boolean useRights, FileShare share, Int32 bufferSize, FileOptions options, SECURITY_ATTRIBUTES secAttrs, String msgPath, Boolean bFromProxy, Boolean useLongPath, Boolean checkHost)
at System.IO.FileStream..ctor(String path, FileMode mode, FileAccess access, FileShare share, Int32 bufferSize, FileOptions options, String msgPath, Boolean bFromProxy)
at System.IO.FileStream..ctor(String path, FileMode mode)
at OfficeOpenXml.ExcelPackage.Save()
InnerException:
Ultimately, I don't really want to even save this, I just want to return it as a FileResult to user, but figured this was a necessary step in getting it setup.