How can I order/sort a PivotTable based on the contents of a DataField PivotField?

I have a page of PivotData (source data) that is used to create a PivotTable on another sheet. I'm doing that like so:

var pch = _xlBook.PivotCaches();
int pivotDataRowsUsed = _xlBook.Worksheets["PivotData"].UsedRange.Rows.Count;
int pivotDataColsUsed = _xlBook.Worksheets["PivotData"].UsedRange.Columns.Count;
string lastColWrittenAsAlpha = ReportRunnerConstsAndUtils.GetExcelColumnName(pivotDataColsUsed);
string endRange = string.Format("{0}{1}", lastColWrittenAsAlpha, pivotDataRowsUsed);

Range sourceData = _xlBook.Worksheets["PivotData"].Range[string.Format("A1:{0}", endRange)];

PivotCache pc = pch.Create(XlPivotTableSourceType.xlDatabase, sourceData);
PivotTable pvt = pc.CreatePivotTable(_xlPivotTableSheet.Range["A6"], "PivotTable");
pvt.MergeLabels = true; // The only thing I noticed this doing was centering the heading labels

pvt.PivotFields("Description").Orientation = XlPivotFieldOrientation.xlRowField;
var monthField = pvt.PivotFields("MonthYr");
monthField.Orientation = XlPivotFieldOrientation.xlColumnField;
monthField.NumberFormat = "mmm yyyy";
monthField.DataRange.Interior.Color = ColorTranslator.ToOle(Color.LightBlue);

// from http://stackoverflow.com/questions/40031858/how-can-i-change-the-text-of-the-automatically-added-labels-on-these-excel-inter
pvt.CompactLayoutColumnHeader = "Months";
pvt.CompactLayoutRowHeader = "Description";

pvt.AddDataField(pvt.PivotFields("TotalQty"), "Total Packages", XlConsolidationFunction.xlSum).NumberFormat = "###,##0";
pvt.AddDataField(pvt.PivotFields("TotalSales"), "Total Purchases", XlConsolidationFunction.xlSum).NumberFormat = "$#,##0";
PivotField avg = pvt.CalculatedFields().Add("Average Price", "=TotalSales/TotalQty", true);
avg.Orientation = XlPivotFieldOrientation.xlDataField;

// TODO: This calculation needs to change (it needs to actually be made a calculation, rather than just the TotalSales val)
pvt.CalculatedFields()._Add("PercentOfTotal", "=TotalSales");
pvt.AddDataField(pvt.PivotFields("PercentOfTotal"), "% of Total", Type.Missing).NumberFormat = "###.##";

// suggestion from http://stackoverflow.com/questions/40003146/how-can-i-get-this-pivottable-to-display-the-values-i-want-it-to-in-the-locatio
pvt.DataPivotField.Orientation = XlPivotFieldOrientation.xlRowField;

The source data is "sort of" in alphabetical order by description, but not really/strictly. The PivotTablization of the source data does alphabetize by Description, though.

Is there a way to prevent the PivotTable from being sorted at all when fed the source data? If so, I imagine the easiest thing to do would be to sort the source data as I want it, which would be easy enough by sorting by the "TotalSales" column descending.

So I either need to change my source data - if I can tell the PivotTable to retain the order of the source data, and not try to sort it itself in any way - OR I need a way to order the data in the PivotTable by a specific DataField PivotField ("TotalSales").

UPDATE

In an attempt to sort by TotalSales, I tried this:

pvt.AddDataField(pvt.PivotFields("TotalSales"), "Total Purchases", XlConsolidationFunction.xlSum).NumberFormat = "$#,##0";
pvt.AddDataField(pvt.PivotFields("TotalSales").SortDescending());

The second line was a total guess, but it compiled; not surprisingly, though, it results in a runtime error.

UPDATE 2

I tried this, too:

pvt.PivotFields("TotalSales").AutoSort(2, "Total Purchases");

...but it didn't do anything.

Upvotes: 2

Views: 1327

Answers (1)

I don't understand why it works, but this does:

var fld = ((PivotField)pvt.PivotFields("Description"));
fld.AutoSort(2, "Total Purchases");

My best guess is that within the Description "umbrella" (which has various "subvalues"), the AutoSort is sorting on Total Purchases, and the "2" arg means descending. At any rate, unintuitive and seemingly undocumented as it is, it does work as I want it to.

Upvotes: 2

Related Questions