我在使用C#中的Epplus生成piviot table时遇到了一些问题。
在生成表之后,我想基于此表创建piviot表:
http://imgur.com/Agxp1mK
在将数据透视表添加到spreedsheet之前一切都很好但是在保存流中添加下面的代码后抛出异常:
类型' System.NullReferenceException'的例外情况发生在EPPlus.dll但未在用户代码中处理 附加信息:对象引用未设置为对象的实例。
在时间配音中,我无法找到空的对象 我的调试轨道:
System.NullReferenceException was unhandled by user code
HResult=-2147467261
Message=Object reference not set to an instance of an object.
Source=EPPlus
StackTrace:
at OfficeOpenXml.ExcelWorksheet.SavePivotTables()
at OfficeOpenXml.ExcelWorksheet.Save()
at OfficeOpenXml.ExcelWorkbook.Save()
at OfficeOpenXml.ExcelPackage.Save()
at OfficeOpenXml.ExcelPackage.SaveAs(Stream OutputStream)
at TestController.GetSpreedsheetPivot(ExcelPackage package, String fileName)
at lambda_method(Closure , ControllerBase , Object[] )
at System.Web.Mvc.ActionMethodDispatcher.Execute(ControllerBase controller, Object[] parameters)
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.ControllerActionInvoker.<>c__DisplayClass15.<InvokeActionMethodWithFilters>b__12()
at System.Web.Mvc.ControllerActionInvoker.InvokeActionMethodFilter(IActionFilter filter, ActionExecutingContext preContext, Func`1 continuation)
代码:
FileInfo newFile = new FileInfo("Excel.xlsx");
ExcelPackage pkg = new ExcelPackage(newFile);
ExcelWorksheet worksheet = pkg.Workbook.Worksheets.Add("Table");
worksheet.Cells["A1"].LoadFromDataTable(table, true); //add datatable values to worksheet
//Create pivot table at A20 using values from A1:F10 named pivTable
var pivotTable = worksheet.PivotTables.Add(worksheet.Cells["H1"], worksheet.Cells["A1:E63"], "pivTable");
//Assign which Rows and Columns of A1:F10 are data or headers
pivotTable.ShowHeaders = true;
pivotTable.FirstHeaderRow = 1;
pivotTable.FirstDataCol = 1;
pivotTable.FirstDataRow = 2;
//Row Labels
pivotTable.RowFields.Add(pivotTable.Fields["Grid"]);
pivotTable.RowFields.Add(pivotTable.Fields["Story"]);
pivotTable.RowFields.Add(pivotTable.Fields["Zone"]);
pivotTable.DataOnRows = false;
pivotTable.DataFields.Add(pivotTable.Fields["Quantity"]);
pivotTable.ColumnFields.Add(pivotTable.Fields["Name of material"]);
var stream = new MemoryStream();
pkg.SaveAs(stream);
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
stream.Position = 0;
return File(stream, contentType, fileName)