EPPlus:如何将工作簿 属性 赋值命令移动到辅助函数?

EPPlus: How can I move workbook property assignment commands to a helper function?

为了提供更多上下文,如果我只想将我的模型导出到我的 ActionResult 中的 Excel 文件,我已经解决了。我学会了为工作簿属性和单元格格式赋值的建议,导出的 Excel 文件正确显示。

我的问题是所有代码都存在于 ActionResult 块中。我想移出将 属性 值分配给单独函数的代码。我遇到的问题是null reference error。下面是完整的 ActionResult 块的粘贴,以提供完整的上下文,以防它暗示我没有考虑过的任何次要问题。

我尝试在控制器中创建一个函数 private ExcelPackage AssignWorkbookProperties(ExcelPackage ep, string exportName),虽然我没有编译时错误,但出现空参数异常。本质上,该函数要么什么也没收到,要么什么也没返回。

有什么方法可以将被阻止的代码移动到辅助函数中吗? (我在此处显示的代码中用注释块表示)。

    public ActionResult ExportToExcel()
    {
        string exportName = "FourCourseAudit";

        // This allows me to export only the columns I want.
        var exportQuery = query.Select(t => new { t.Campus, t.Student_Name, t.Course_Count });

        // epp is the model where I gather the predefined property values
        var epp = new ExportToExcelProperties();
        var prop = epp.WorkbookProperties.Where(t => t.ExportName == exportName);

        try
        {                                
            byte[] response;                
            using (var excelFile = new ExcelPackage())
            {   
                // Define worksheet data.
                var worksheet = excelFile.Workbook.Worksheets.Add("Sheet1");                    

                /* ------------------------------------------------------------------ */
                /* -------------Begin: Move to helper function ---------------------- */
                /* ------------------------------------------------------------------ */

                // Define workbook properties.
                var workbookProperties = excelFile.Workbook.Properties;

                workbookProperties.Author = HttpContext.User.Identity.Name;
                workbookProperties.Title = prop.Select(t => t.Title).ToString();
                workbookProperties.Comments = prop.Select(t => t.Comments).ToString();
                workbookProperties.Created = DateTime.Now;
                workbookProperties.Category = prop.Select(t => t.Category).ToString();


                // Define worksheet contextual data.
                worksheet.Cells["A1"].Value = "Title: ";
                worksheet.Cells["A2"].Value = "Export Date: ";

                worksheet.Cells["A1:A2"].Style.Font.Bold = true;

                worksheet.Cells["B1"].Value = prop.Select(t => t.Title).ToString();
                worksheet.Cells["B2"].Value = DateTime.Now;
                worksheet.Cells["B2"].Style.Numberformat.Format = "mm/dd/yyyy hh:mm";

                worksheet.Cells["A1:B2"].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Medium);
                worksheet.Cells["A1:B2"].AutoFitColumns();

                Color bgColor = ColorTranslator.FromHtml("#2956B2");

                worksheet.Cells["A1:B2"].Style.Fill.PatternType = ExcelFillStyle.Solid;
                worksheet.Cells["A1:B2"].Style.Fill.BackgroundColor.SetColor(bgColor);
                worksheet.Cells["A1:B2"].Style.Font.Color.SetColor(Color.White);

                worksheet.Cells["D1:F1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
                worksheet.Cells["D1:F1"].Style.Fill.BackgroundColor.SetColor(bgColor);
                worksheet.Cells["D1:F1"].Style.Font.Color.SetColor(Color.White);

                /* ------------------------------------------------------------------ */
                /* ---------------End: Move to helper function ---------------------- */
                /* ------------------------------------------------------------------ */

                worksheet
                    .Cells["D1"]
                    .LoadFromCollection(Collection: exportQuery, PrintHeaders: true)                        
                    .Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);



                worksheet.Cells["A1:F200"].AutoFitColumns();

                response = excelFile.GetAsByteArray();
            }
            return File(response, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Export.xlsx");
        }
        catch (NullReferenceException) {
            return ViewBag.Errormsg = "There was a null reference exception.";
        }
        catch (ArgumentNullException)
        {
            return ViewBag.Errormsg = "There was an argument null exception.";
        }
    }

我找到了 resource 帮助我解决了问题。

问题是我的函数返回并接受了错误的对象。

我创建了两个不同的函数。第一个函数 returns 键入 ExcelWorksheet,第二个函数 returns 键入 OfficeProperties。这两个函数都有 ExcelPackage 作为输入参数。

首先,这是 ActionResult 现在的干净程度:

    public ActionResult ExportToExcel()
    {
        string exportName = "FourCourseAudit";

        // This allows me to export only the columns I want.
        var exportQuery = query.Select(t => new { t.Campus, t.Student_Name, t.Course_Count });          

        try
        {                                
            byte[] response;                
            using (var excelFile = new ExcelPackage())
            {   
                // Use helper functions to fill worksheet and workbook definitions
                var worksheet = CreateSheet(excelFile,exportName);
                var workbook = AssignProperties(excelFile,exportName);

                // Fill worksheet with data to export
                worksheet
                    .Cells["D1"]
                    .LoadFromCollection(Collection: exportQuery, PrintHeaders: true)                        
                    .Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Thin);

                worksheet.Cells["A1:F200"].AutoFitColumns();

                response = excelFile.GetAsByteArray();
            }
            return File(response, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", "Export.xlsx");
        }
        catch (NullReferenceException) {
            return ViewBag.Errormsg = "There was a null reference exception.";
        }
        catch (ArgumentNullException)
        {
            return ViewBag.Errormsg = "There was an argument null exception.";
        }
    }

目前,这两个函数在同一个控制器中。我越了解如何概括它们,我可能会将它们移到其他地方。

    private static ExcelWorksheet CreateSheet(ExcelPackage p,string exportName)
    {
        var epp = new ExportToExcelProperties().WorkbookProperties;
        var prop = epp.Where(t => t.ExportName == "FourCourseAudit").Select(t=>t.Title).Single();

        string sheetName = "Sheet1";
        p.Workbook.Worksheets.Add(sheetName);
        ExcelWorksheet worksheet = p.Workbook.Worksheets[1];
        worksheet.Name = sheetName; //Setting Sheet's name
        worksheet.Cells.Style.Font.Size = 11; //Default font size for whole sheet
        worksheet.Cells.Style.Font.Name = "Calibri"; //Default Font name for whole sheet

        // Define worksheet contextual data.
        worksheet.Cells["A1"].Value = "Title: ";
        worksheet.Cells["A2"].Value = "Export Date: ";

        worksheet.Cells["A1:A2"].Style.Font.Bold = true;

        worksheet.Cells["B1"].Value = prop;
        worksheet.Cells["B2"].Value = DateTime.Now;
        worksheet.Cells["B2"].Style.Numberformat.Format = "mm/dd/yyyy hh:mm";

        worksheet.Cells["A1:B2"].Style.Border.BorderAround(OfficeOpenXml.Style.ExcelBorderStyle.Medium);
        worksheet.Cells["A1:B2"].AutoFitColumns();

        Color bgColor = ColorTranslator.FromHtml("#2956B2");

        worksheet.Cells["A1:B2"].Style.Fill.PatternType = ExcelFillStyle.Solid;
        worksheet.Cells["A1:B2"].Style.Fill.BackgroundColor.SetColor(bgColor);
        worksheet.Cells["A1:B2"].Style.Font.Color.SetColor(Color.White);

        worksheet.Cells["D1:F1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
        worksheet.Cells["D1:F1"].Style.Fill.BackgroundColor.SetColor(bgColor);
        worksheet.Cells["D1:F1"].Style.Font.Color.SetColor(Color.White);

        return worksheet;
    }

    private static OfficeProperties AssignProperties(ExcelPackage p, string exportName)
    {
        // epp is the model where I gather the predefined property values
        var epp = new ExportToExcelProperties().WorkbookProperties;
        var query = from t in epp
                    where t.ExportName == exportName
                    select new { t.Title, t.Comments, t.Category };
        var title = query.Select(t=>t.Title).Single();
        var comments = query.Select(t=>t.Comments).Single();
        var category = query.Select(t=>t.Category).Single();

        OfficeProperties workbookProperties = p.Workbook.Properties;
        workbookProperties.Author = System.Web.HttpContext.Current.User.Identity.Name;
        workbookProperties.Title = title;
        workbookProperties.Comments = comments;
        workbookProperties.Created = DateTime.Now;
        workbookProperties.Category = category;

        return workbookProperties;
    }

这直接回答了我如何将工作表 属性 代码移到 ActionResult 之外的问题,但我可以清楚地看到可以做更多的工作来概括代码并使其更加模块化。