我正在尝试在 MVC 应用程序的控制器中使用 EPPLUS 创建一个 Excel 文件。
该文件似乎创建得很好,但是当我尝试保存时会窒息:
[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();
}
我得到的错误: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:
最终,我什至不想保存它,我只想将它作为 FileResult 返回给用户,但认为这是设置它的必要步骤。