我有这个 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
}
这有点奏效;我在工作表上得到了这个:
如果我然后(手动)选择工作表 NE 角的“数据透视表字段列表”中的所有六个可用字段,数据透视表将其外观更改为:
这非常好,因为用户可以“搞乱”它——为每个字段选择可用数据的任何子集。但我希望数据透视表以这种状态开始,而不是用户必须手动选择字段。
这怎么可能?
注意:我在使用 Excel Interop 时遇到了类似的问题,并发现使用 EPPlus 与此相比,“事情”要容易得多;尽管如此,以编程方式选择字段似乎是一个挑战......