保存excel时EPPlus会抛出NullReferenceException

时间:2018-06-08 00:26:38

标签: c# epplus

我使用EPPlus生成Excel。

这是我的行动

 public ActionResult ExportReportToExcel()
    {
        var model = new ReportingViewModel();
        int numOfInvolvedCompanies, numOfRefusedCompanies, numOfSuccessfullCompanies, numOfEmployeesInvolved, projectsCount;
        model.Projects = db.GetProjectsReport(1, 1, out projectsCount, out numOfInvolvedCompanies, out numOfRefusedCompanies, out numOfSuccessfullCompanies, out numOfEmployeesInvolved);
        model.AllProjectsReport.NumberOfCompanyInvolved = numOfInvolvedCompanies;
        model.AllProjectsReport.NumberOfRefusedCompanies = numOfRefusedCompanies;
        model.AllProjectsReport.NumberOfSuccessfullParticipated = numOfSuccessfullCompanies;
        model.AllProjectsReport.NumberOfEmployeeInvolved = numOfEmployeesInvolved;

        ExcelPackage excel =  ExcelGenerator.GenerateReportingExcel(model);

        string excelName = "Reporting";

        using (var memoryStream = new MemoryStream())
        {
            try
            {
                Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
                Response.AddHeader("content-disposition", "attachment; filename=" + excelName + ".xlsx");
                excel.SaveAs(memoryStream);
                memoryStream.WriteTo(Response.OutputStream);
                Response.Flush();
                Response.End();
            }
            catch(Exception e)
            {
                throw;
            }

        }

        return RedirectToAction("Reporting");
    }

这是我生成excel的方法

        public static ExcelPackage GenerateReportingExcel(ReportingViewModel model)
    {
        using (ExcelPackage excel = new ExcelPackage())
        {
            var workSheet = excel.Workbook.Worksheets.Add("Reporting");

            workSheet.TabColor = System.Drawing.Color.Black;
            workSheet.DefaultRowHeight = 12;
            workSheet.Row(1).Height = 20;
            workSheet.Row(1).Style.HorizontalAlignment = ExcelHorizontalAlignment.Center;
            workSheet.Row(1).Style.Font.Bold = true;

            workSheet.Cells[1, 1].Value = "Name";
            workSheet.Cells[1, 2].Value = "Sector";
            workSheet.Cells[1, 3].Value = "N of companies involved";
            workSheet.Cells[1, 4].Value = "N of refused companies";
            workSheet.Cells[1, 5].Value = "N of successful participated";
            workSheet.Cells[1, 6].Value = "N of employee involved";
            workSheet.Cells[1, 7].Value = "Start date";
            workSheet.Cells[1, 8].Value = "Finish date";



            int i = 2;
            foreach (var item in model.Projects)
            {
                workSheet.Cells[i, 1].Value = item.Name;
                workSheet.Cells[i, 2].Value = item.SectorValues;
                workSheet.Cells[i, 3].Value = item.NumberOfCompanyInvolved;
                workSheet.Cells[i, 4].Value = item.NumberOfRefusedCompanies;
                workSheet.Cells[i, 5].Value = item.NumberOfSuccessfullParticipated;
                workSheet.Cells[i, 6].Value = item.NumberOfEmployeeInvolved;
                workSheet.Cells[i, 7].Value = item.StartDate;
                workSheet.Cells[i, 8].Value = item.FinishDate;
                i++;
            }


            workSheet.Cells[i, 2].Value = "Total";
            workSheet.Cells[i, 3].Value = model.AllProjectsReport.NumberOfCompanyInvolved;
            workSheet.Cells[i, 4].Value = model.AllProjectsReport.NumberOfRefusedCompanies;
            workSheet.Cells[i, 5].Value = model.AllProjectsReport.NumberOfSuccessfullParticipated;
            workSheet.Cells[i, 6].Value = model.AllProjectsReport.NumberOfEmployeeInvolved;


            for (int colNum = 1; colNum <= 8; colNum++)
            {
                workSheet.Column(colNum).AutoFit();
            }

            return excel;
        }
    }

尝试保存excel时会抛出NullReferenceException excel.SaveAs(memoryStream)行

enter image description here

本案的有趣之处在于它在2天前工作。突然它停止工作,现在抛出了这个错误。

1 个答案:

答案 0 :(得分:1)

此处的问题出在GenerateReportingExcel方法中。

在该方法中,您将返回在using语句中创建的ExcelPackage对象。

using (ExcelPackage excel = new ExcelPackage())
{
      ...         
      return excel;
}

由于using创建的一次性对象将在您退出块后立即处理,因此在excel.SaveAs(memoryStream)之外使用此对象将导致excel上的例外,因为excel.SaveAs();已经存在地布置。

您必须移动一些代码才能解决此问题。两种可能的解决方案(取决于您的需求)是:

  1. GenerateReportingExcel()电话移至using,以便在创建excel
  2. using块内进行
  3. 移除ExcelPackage块并手动创建已退回的excel.Dispose()对象,然后在ExportReportToExcel()完成后再拨打public static ExcelPackage GenerateReportingExcel(ReportingViewModel) { var excel = new ExcelPackage(); ... return excel; }
  4. ExportReportToExcel()

    然后在try { ... excel.SaveAs(memoryStream); excel.Dispose(); ... }

    SELECT usuario,SUM(hojas)AS sum 
    FROM trabajo 
    WHERE MONTH(fecha)='5' 
    GROUP BY usuario 
    ORDER BY SUM DESC 
    LIMIT 0,10;