如何预先选择要包含在数据透视表中的字段?

时间:2016-08-04 22:43:41

标签: c# excel pivot-table epplus epplus-4

我有这个EPPlus代码来创建数据透视表:

private void AddPivotTable()
{
    string colAlphaRowNum = string.Format("A{0}", locationWorksheet.Dimension.End.Row+5);
    ExcelAddressBase eab = locationWorksheet.Cells[colAlphaRowNum];
    ExcelRangeBase erb = locationWorksheet.Cells[6, 1, locationWorksheet.Dimension.End.Row, locationWorksheet.Dimension.End.Column];
    var pt = locationWorksheet.PivotTables.Add(eab, erb, "Pivotous");

    pt.MultipleFieldFilters = true;
    pt.RowGrandTotals = true;
    pt.ColumGrandTotals = true;
    pt.Compact = true;
    pt.CompactData = true;
    pt.GridDropZones = false;
    pt.Outline = false;
    pt.OutlineData = false;
    pt.ShowError = true;
    pt.ErrorCaption = "[error]";
    pt.ShowHeaders = true;
    pt.UseAutoFormatting = true;
    pt.ApplyWidthHeightFormats = true;
    pt.ShowDrill = true;
    pt.DataOnRows = false;

    pt.FirstHeaderRow = 1;  // first row has headers
    pt.FirstDataCol = 1;    // first col of data
    pt.FirstDataRow = 2;    // first row of data

    pt.TableStyle = TableStyles.Medium6; // There is a "custom" and several Dark, Light, and Medium options
}

这种类型的工作;我在表格上看到了这个:

enter image description here

如果我然后(手动)选择工作表NE角落的“数据透视表字段列表”中的所有六个可用字段,数据透视表会将其显示更改为:

enter image description here

这非常好,因为用户可以“乱搞”它 - 为每个字段选择任何可用数据子集。但我希望数据透视表在此状态下启动,而不是用户手动选择字段所必需的。

这怎么可能?

注意:我在使用Excel Interop时遇到了类似的问题,并发现使用EPPlus“事物”要容易得多;但是,编程选择字段仍然是一个挑战......

1 个答案:

答案 0 :(得分:1)

比Excel Interop更容易;这就是全部:

pt.RowFields.Add(pt.Fields[0]);
pt.RowFields.Add(pt.Fields[1]);
pt.RowFields.Add(pt.Fields[2]);
pt.RowFields.Add(pt.Fields[3]);
pt.RowFields.Add(pt.Fields[4]);
pt.RowFields.Add(pt.Fields[5]);