为了提供更多上下文,如果我只是想将我的模型导出到ActionResult中的Excel文件中,那么我已经解决了这个问题。我学会了将值分配给工作簿属性和单元格格式,并且导出的Excel文件正确显示。
我的问题是ActionResult块中存在所有代码。我想移出将属性值分配给单独函数的代码。我遇到的问题是null reference error
。下面是完整ActionResult块的粘贴,以提供完整的上下文,如果它表明我没有考虑任何次要问题。
我尝试在控制器private ExcelPackage AssignWorkbookProperties(ExcelPackage ep, string exportName)
中创建一个函数,虽然我没有编译时错误,但是有一个null参数异常。从本质上讲,该功能要么一无所获,要么一无所返。
有什么方法可以将阻止的代码移动到辅助函数中吗? (我在此处显示的代码中用注释块表示。)
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.";
}
}
答案 0 :(得分:0)
我找到了resource帮助我找出问题所在。
问题是我的功能正在返回并接受错误的对象。
我创建了两个不同的功能。第一个函数返回类型ExcelWorksheet
,第二个函数返回类型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之外移动工作表属性代码的问题,但是我可以清楚地看到可以做更多工作来概括代码并使其更加模块化。