我在.Net中使用EPPlus并创建了一个包含行字段和一个摘要数据字段的数据透视表。
有谁知道如何从数据透视表创建图表?我不知道数据透视表的范围。
这是我的代码:
static void DT2XL(DataTable dt, ExcelPackage excel)
{
var wsData = excel.Workbook.Worksheets["Eco-Data"];
var wsPivot = excel.Workbook.Worksheets["Eco-Pivot"];
if (wsData == null) wsData = excel.Workbook.Worksheets.Add("Eco-Data");
if (wsPivot == null) wsPivot = excel.Workbook.Worksheets.Add("Eco-Pivot");
wsData.Cells["A1"].LoadFromDataTable(dt, true, OfficeOpenXml.Table.TableStyles.Medium6);
foreach (DataColumn col in dt.Columns)
{
if (col.DataType == typeof(System.DateTime))
{
var colNumber = col.Ordinal + 1;
var range = wsData.Cells[2, colNumber, dt.Rows.Count + 1, colNumber];
range.Style.Numberformat.Format = "dd.MM.yyyy";
}
}
var dataRange = wsData.Cells[wsData.Dimension.Address.ToString()];
dataRange.AutoFitColumns();
var pivotTable = wsPivot.PivotTables.Add(wsPivot.Cells["A1"], dataRange, "EcoPivotTable");
pivotTable.MultipleFieldFilters = true;
pivotTable.RowGrandTotals = true;
pivotTable.ColumGrandTotals = true;
pivotTable.Compact = true;
pivotTable.CompactData = true;
pivotTable.GridDropZones = false;
pivotTable.Outline = false;
pivotTable.OutlineData = false;
pivotTable.ShowError = true;
pivotTable.ErrorCaption = "[error]";
pivotTable.ShowHeaders = true;
pivotTable.UseAutoFormatting = true;
pivotTable.ApplyWidthHeightFormats = true;
pivotTable.ShowDrill = true;
pivotTable.FirstDataCol = 3;
pivotTable.RowHeaderCaption = "Үзүүлэлтүүд";
pivotTable.GrandTotalCaption = "Нийт";
foreach (DataColumn c in dt.Columns)
{
var field = pivotTable.Fields[c.ColumnName];
if (c.ColumnName.ToLower().StartsWith("column") ||
c.ColumnName.ToLower().StartsWith("row"))
pivotTable.RowFields.Add(field);
else if (c.ColumnName.ToLower().StartsWith("data"))
pivotTable.DataFields.Add(field);
}
//I want to create a chart from 'pivotTable'
//...
//...
//...
//...
//...
}
谢谢!
答案 0 :(得分:2)
以下是创建数据透视图的代码:
var reportFilterNames = new List<string>(); //TODO: Fill with column names from DataTable
var valueNames = new List<string>(); //TODO: Fill with column names from DataTable
ExcelWorksheet dataWorksheet = package.Workbook.Worksheets[report.ReportType];
ExcelRange dataRange = dataWorksheet.Cells["A1:" + dataWorksheet.Dimension.End.Address];
ExcelWorksheet pivotWorksheet = package.Workbook.Worksheets.Add(dt.TableName);
ExcelRange pivotDataRange = pivotWorksheet.Cells["A" + (2 + reportFilterNames.Count)];
ExcelPivotTable pivotTable = pivotWorksheet.PivotTables.Add(pivotDataRange, dataRange, "Stats");
pivotTable.DataOnRows = false;
pivotTable.RowFields.Add(pivotTable.Fields["DATE"]);
foreach (string reportFilterName in reportFilterNames)
pivotTable.PageFields.Add(pivotTable.Fields[reportFilterName]);
foreach (string valueName in valueNames)
pivotTable.DataFields.Add(pivotTable.Fields[valueName]);
var chart = pivotWorksheet.Drawings.AddChart("PivotChart", eChartType.Line, pivotTable);
chart.SetPosition(1, 0, 4, 0);
chart.SetSize(1200, 800);