简体   繁体   English

激活C#中数据透视表总计的显示详细信息

[英]Activating Show Details for Grand Total of Pivot Table in C#

I'm trying to automate the creation of "Show Detail" of a Pivot Table from Excel using C# 我正在尝试使用C#从Excel自动创建数据透视表的“显示详细信息”

using Excel = Microsoft.Office.Interop.Excel;

My code: 我的代码:

var excelApp = new Excel.Application();
excelApp.Visible = true;
Excel.Workbook workbook = excelApp.Workbooks.Open(@"D:\path_to_excel_file.xlsm");
Excel.Worksheet worksheet = (Excel.Worksheet)workbook.Worksheets["Sheet_Name"];

Excel.PivotTable pivot = worksheet.PivotTables("defined_pivot_table_name");
pivot.DataBodyRange.ShowDetail = true;

The code works, but it displays only the details of the first "Total" value. 该代码可以工作,但是只显示第一个“总计”值的详细信息。 But what I want is to get the "Show Details" of the "Grand Total". 但是我想要的是获取“总计”的“显示详细信息”。 In this case for this pivot table, it will create a new sheet with the 4 elements, but what I want is for the Grand Total (202). 在这种情况下,对于此数据透视表,它将创建一个包含4个元素的新工作表,但我想要的是总计(202)。

在此处输入图片说明

I've tried selecting it first by pivot.PivotSelect("Grand Total"); 我尝试过首先通过pivot.PivotSelect("Grand Total"); but still no results. 但仍然没有结果。 I've also checked pivot.RowGrand and pivot.ColumnGrand which both return True. 我还检查了pivot.RowGrandpivot.ColumnGrand ,它们都返回True。

Maybe this can help 也许可以帮助

// Access the pivot table by its name in the collection. 
PivotTable pivotTable = worksheet.PivotTables["PivotTable1"];


// Access the pivot field by its name in the collection. 
PivotField field = pivotTable.Fields["Category"];


// Display multiple subtotals for the field.   
field.SetSubtotal(PivotSubtotalFunctions.Sum | PivotSubtotalFunctions.Average);

// Show all subtotals at the bottom of each group. 
pivotTable.Layout.ShowAllSubtotals(false);

// Hide grand totals for rows.
pivotTable.Layout.ShowRowGrandTotals = False

// Hide grand totals for columns.
pivotTable.Layout.ShowColumnGrandTotals = False

// custom label for grand totals
pivotTable.View.GrandTotalCaption = "Total Sales";

If your pivottable has both, RowGrand AND ColumnGrand , then it also has a grand total 如果您的数据透视表同时具有RowGrandColumnGrand ,则它也具有总计

if (pivot.RowGrand && pivot.ColumnGrand)

Then you can use the last cell of the pivottable's TableRange1 to generate the details by ShowDetail 然后,您可以使用数据透视表的TableRange1的最后一个单元格通过ShowDetail生成详细信息

int countRows = pivot.TableRange1.Rows.Count;
int countColumns = pivot.TableRange1.Columns.Count;
pivot.TableRange1.Cells[countRows, countColumns].ShowDetail = true;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM