I am writing a C # program that opens and reads an Excel document and creates a pivot table with some fields. One field is added as rows. The rest are calculated data fields. Everything works and the data is added in order. There is only one problem. Computed data fields are also added as rows, but I would like to have them as columns. In Excel, this manually means dragging values from rows to columns. But how can I achieve the same programmatically?
My code is:
Excel.PivotTable pivot1 = xlSheet.PivotTableWizard(
Excel.XlPivotTableSourceType.xlDatabase,
pivotRange,
xlSheet.get_Range(Constants.PLACE_PIVOT_1),
"Grade",
false,
false,
true,
false,
missing,
missing,
false,
false,
Excel.XlOrder.xlDownThenOver,
missing,
missing,
missing);
Excel.PivotField betygField =
(Excel.PivotField)pivot1.PivotFields("Grade type");
betygField.Orientation =
Excel.XlPivotFieldOrientation.xlRowField;
betygField.Position = 1;
for (int f = Constants.START_START_SAMMAN; f < columns; f++)
{
string name = Convert.ToString(xlSheet.Cells[Constants.BEGIN_STAT_SAMMAN_Y, f].Value);
Excel.PivotField f1 = pivot1.AddDataField((Excel.PivotField)pivot1.PivotFields(name),
String.Format("Sume of {0}", name), Excel.XlConsolidationFunction.xlSum);
Excel.PivotField f2 = pivot1.AddDataField((Excel.PivotField)pivot1.PivotFields(name),
String.Format("Avg. of {0}", name), Excel.XlConsolidationFunction.xlAverage);
f1.Orientation =
Excel.XlPivotFieldOrientation.xlDataField;
f1.NumberFormat = "0.00";
f2.Orientation =
Excel.XlPivotFieldOrientation.xlDataField;
f2.NumberFormat = "0.00";
}
pivot1.GrandTotalName = "Totalt";
pivot1.RowGrand = true;
pivot1.ColumnGrand = true;
pivot1.TableStyle2 = "PivotStyleLight16";
source
share