Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EPPlus pivot tables/charts

Tags:

c#

asp.net

epplus

I've been using EPPlus for .net for a while now but only for simple data manipulation. Are there any examples somewhere on how to use it to create pivot tables/charts? It seems to support it as I can see PivotTable in the intellisense but just unsure on the syntax.

I could only find the likes of pie/bar charts in the samples provided.

like image 890
user1468537 Avatar asked Jul 25 '12 12:07

user1468537


2 Answers

I've produced a similar solution from Tim's Answer. First, I defined a simple interface that I use as part of my export methods:

public interface IPivotTableCreator
{
    void CreatePivotTable(
        OfficeOpenXml.ExcelPackage pkg, // reference to the destination book
        string tableName,               // "tab" name used to generate names for related items
        string pivotRangeName);         // Named range in the Workbook refers to data
}

Then I implemented a simple class that hold the variable values and procedural code to do the work:

public class SimplePivotTable : IPivotTableCreator
{
    List<string> _GroupByColumns;
    List<string> _SummaryColumns;
    /// <summary>
    /// Constructor
    /// </summary>
    public SimplePivotTable(string[] groupByColumns, string[] summaryColumns)
    {
        _GroupByColumns = new List<string>(groupByColumns);
        _SummaryColumns = new List<string>(summaryColumns);
    }

    /// <summary>
    /// Call-back handler that builds simple PivatTable in Excel
    /// http://stackoverflow.com/questions/11650080/epplus-pivot-tables-charts
    /// </summary>
    public void CreatePivotTable(OfficeOpenXml.ExcelPackage pkg, string tableName, string pivotRangeName)
    {
        string pageName = "Pivot-" + tableName.Replace(" ", "");
        var wsPivot = pkg.Workbook.Worksheets.Add(pageName);
        pkg.Workbook.Worksheets.MoveBefore(PageName, tableName);

        var dataRange = pkg.Workbook./*Worksheets[tableName].*/Names[pivotRangeName];
        var pivotTable = wsPivot.PivotTables.Add(wsPivot.Cells["C3"], dataRange, "Pivot_" + tableName.Replace(" ", ""));
        pivotTable.ShowHeaders = true;
        pivotTable.UseAutoFormatting = true;
        pivotTable.ApplyWidthHeightFormats = true;
        pivotTable.ShowDrill = true;
        pivotTable.FirstHeaderRow = 1;  // first row has headers
        pivotTable.FirstDataCol = 1;    // first col of data
        pivotTable.FirstDataRow = 2;    // first row of data

        foreach (string row in _GroupByColumns)
        {
            var field = pivotTable.Fields[row];
            pivotTable.RowFields.Add(field);
            field.Sort = eSortType.Ascending;
        }

        foreach (string column in _SummaryColumns)
        {
            var field = pivotTable.Fields[column];
            ExcelPivotTableDataField result = pivotTable.DataFields.Add(field);
        }

        pivotTable.DataOnRows = false;
    }
}

Then I create an instance of my SimplePivotTable creator class:

IPivotTableCreator ptCreator = new SimplePivotTable(
    new string[] { "OrganizationTitle", "GroupingTitle", "DetailTitle" }, /* collapsible rows */
    new string[] { "Baseline", "Increase", "Decrease", "NetChange", "CurrentCount"}); /* summary columns */

I have a third class that currently exposes about six different methods to take one-or-more data sets (usually List objects) and turn each of the data sets into a worksheet of data with a named range for the data. Now, I'm adapting those export methods to allow me to generate Pivot Tables for any/all of those export methods. They all do something like this:

OfficeOpenXml.ExcelPackage pkg = new ExcelPackage();
ExportCollectionToExcel(pkg, tableName, dataset);   // Create worksheet filled with data
                                                    // Creates a NamedRange of data
ptCreator.CreatePivotTable(pkg, tableName, GetPivotRangeName(tableName));

By using an interface, I leave open more opportunities (I think) to generate, for example, a different pivot table for multiple sheets. My basic SimplePivotTable class just used for a single table with some specific assumptions, but it wouldn't be hard to put the configuration data into a dictionary keyed to the Table names.

Hope that helps someone.

like image 163
Ted H. Avatar answered Oct 21 '22 00:10

Ted H.


Here's the code of a pivot i've created recently, maybe it does help:

DataTable table = getDataSource();
FileInfo fileInfo = new FileInfo(path);
var excel = new ExcelPackage(fileInfo);
var wsData = excel.Workbook.Worksheets.Add("Data-Worksheetname");
var wsPivot = excel.Workbook.Worksheets.Add("Pivot-Worksheetname");
wsData.Cells["A1"].LoadFromDataTable(table, true, OfficeOpenXml.Table.TableStyles.Medium6);
if (table.Rows.Count != 0)
{
    foreach (DataColumn col in table.Columns)
    {
        // format all dates in german format (adjust accordingly)
        if (col.DataType == typeof(System.DateTime))
        {
            var colNumber = col.Ordinal + 1;
            var range = wsData.Cells[2, colNumber, table.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["A3"], dataRange, "Pivotname");
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 = "Claims";

var modelField = pivotTable.Fields["Model"];
pivotTable.PageFields.Add(modelField);
modelField.Sort = OfficeOpenXml.Table.PivotTable.eSortType.Ascending;

var countField = pivotTable.Fields["Claims"];
pivotTable.DataFields.Add(countField);

var countryField = pivotTable.Fields["Country"];
pivotTable.RowFields.Add(countryField);
var gspField = pivotTable.Fields["GSP / DRSL"];
pivotTable.RowFields.Add(gspField);

var oldStatusField = pivotTable.Fields["Old Status"];
pivotTable.ColumnFields.Add(oldStatusField);
var newStatusField = pivotTable.Fields["New Status"];
pivotTable.ColumnFields.Add(newStatusField);

var submittedDateField = pivotTable.Fields["Claim Submitted Date"];
pivotTable.RowFields.Add(submittedDateField);
submittedDateField.AddDateGrouping(OfficeOpenXml.Table.PivotTable.eDateGroupBy.Months | OfficeOpenXml.Table.PivotTable.eDateGroupBy.Days);
var monthGroupField = pivotTable.Fields.GetDateGroupField(OfficeOpenXml.Table.PivotTable.eDateGroupBy.Months);
monthGroupField.ShowAll = false;
var dayGroupField = pivotTable.Fields.GetDateGroupField(OfficeOpenXml.Table.PivotTable.eDateGroupBy.Days);
dayGroupField.ShowAll = false;

excel.Save();
like image 22
Tim Schmelter Avatar answered Oct 20 '22 23:10

Tim Schmelter