简体   繁体   中英

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#

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).

在此处输入图片说明

I've tried selecting it first by pivot.PivotSelect("Grand Total"); but still no results. I've also checked pivot.RowGrand and pivot.ColumnGrand which both return 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

if (pivot.RowGrand && pivot.ColumnGrand)

Then you can use the last cell of the pivottable's TableRange1 to generate the details by ShowDetail

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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