首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >EPPlus数据透视表/图表

EPPlus数据透视表/图表
EN

Stack Overflow用户
提问于 2012-07-25 20:48:17
回答 2查看 26K关注 0票数 23

我在.net中使用EPPlus已经有一段时间了,但只用于简单的数据操作。有没有关于如何使用它来创建数据透视表/图表的例子?它似乎支持它,因为我可以在智能感知中看到PivotTable,但只是不确定语法。

我只能在提供的示例中找到类似饼图/条形图的内容。

EN

回答 2

Stack Overflow用户

发布于 2012-12-21 04:19:45

我从Tim的答案中得出了一个类似的解决方案。首先,我定义了一个简单的接口,作为导出方法的一部分:

代码语言:javascript
复制
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
}

然后我实现了一个简单的类来保存变量值和过程代码来完成这项工作:

代码语言:javascript
复制
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;
    }
}

然后,我创建了SimplePivotTable创建器类的一个实例:

代码语言:javascript
复制
IPivotTableCreator ptCreator = new SimplePivotTable(
    new string[] { "OrganizationTitle", "GroupingTitle", "DetailTitle" }, /* collapsible rows */
    new string[] { "Baseline", "Increase", "Decrease", "NetChange", "CurrentCount"}); /* summary columns */

我还有第三个类,它目前公开了大约六种不同的方法,以获取一个或多个数据集(通常是列表对象),并将每个数据集转换为具有数据命名范围的数据工作表。现在,我正在调整这些导出方法,以允许我为任何/所有这些导出方法生成透视表。它们都是这样做的:

代码语言:javascript
复制
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));

通过使用接口,我留下了更多的机会(我认为)来生成,例如,为多个工作表生成不同的透视表。我的基本SimplePivotTable类仅用于带有一些特定假设的单个表,但是将配置数据放入与表名相关的字典中并不困难。

希望这能帮助到一些人。

票数 28
EN

Stack Overflow用户

发布于 2012-07-25 21:01:15

这是我最近创建的pivot的代码,也许它确实有帮助:

代码语言:javascript
复制
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();
票数 15
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/11650080

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档