After much gnashing of teeth, &c, I was able to achieve a modicum of success with generating a PivotTable. It now sports both a "row filter" (on the Descriptions) and a "column filter" (on the "month year" columns), like so:
This is accomplished with the following code:
var pch = _xlBook.PivotCaches();
Range sourceData = _xlBook.Worksheets["PivotData"].Range["A1:G318"]; // TODO: Make range dynamic
PivotCache pc = pch.Create(XlPivotTableSourceType.xlDatabase, sourceData);
PivotTable pvt = pc.CreatePivotTable(_xlPivotTableSheet.Range["A8"], "PivotTable");
pvt.PivotFields("Description").Orientation = XlPivotFieldOrientation.xlRowField;
pvt.PivotFields("MonthYr").Orientation = XlPivotFieldOrientation.xlColumnField;
The source data ("PivotData") looks like this:
What the PivotTable should look like, when all is said and coded, is this:
What do I need to do to achieve this look (this data, and in these locations)? I reckon part of it is has to do with the assignments of more XlPivotFieldOrientation values to more PivotFields, but don't know just what they should be.
And first but possibly least (but still important), "Row Labels" should say "Description" and "Column Labels" should say "Month"
UPDATE
I am trying to add, piece by piece, the code needed to make the various columns display. I tried this:
pvt.AddDataField(pvt.PivotFields("TotalQty"), "Total Packages", XlConsolidationFunction.xlSum).NumberFormat = "###,##0";
...hoping that the data from the source data's "TotalQty" column would display in a column headed "Total Packages"
It does indeed display, but the label "Total Packages", appears in an odd/out-of-the-way place:
How can I get the "Total Packages" label to display where it does in the "model" screenshot?
UPDATE 2
Hambone mentioned my TODO in his answer; I got back to it and made that dynamic this way:
int rowsUsed = _xlBook.Worksheets["PivotData"].UsedRange.Rows.Count;
int colsUsed = _xlBook.Worksheets["PivotData"].UsedRange.Columns.Count;
string colsUsedAsAlpha = GetExcelColumnName(colsUsed);
string endRange = string.Format("{0}{1}", colsUsedAsAlpha, rowsUsed);
Range sourceData = _xlBook.Worksheets["PivotData"].Range[string.Format("A1:{0}",
endRange)];
// Pass "1", get "A", etc.; from http://stackoverflow.com/questions/181596/how-
to-convert-a-column-number-eg-127-into-an-excel-column-eg-aa
public static string GetExcelColumnName(int columnNumber)
{
int dividend = columnNumber;
string columnName = String.Empty;
while (dividend > 0)
{
var modulo = (dividend - 1) % 26;
columnName = Convert.ToChar(65 + modulo).ToString() + columnName;
dividend = (dividend - modulo) / 26;
}
return columnName;
}
BTW, I can't find my bronze badges.