Excel Integration and DataField Orientation

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, // source type
                 pivotRange, // source
                 xlSheet.get_Range(Constants.PLACE_PIVOT_1), //destination
                 "Grade", // table name 
                 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;

            // int dataIndex = 2;
            for (int f = Constants.START_START_SAMMAN; f < columns; f++) //add some array of columns as DataFields
            {
                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";
+4
source share
1 answer

You already know this trick ...

, - Excel, , ( . ). VBA #, interop Excel, VB, .

How to find the macro recorder

, . , , Orientation and Position.

The drag and drop action

The recorded macro

+4

Source: https://habr.com/ru/post/1529415/


All Articles