2014-02-28 141 views
4

我正在写一个C#程序,它打开并读取一个Excel文档,并创建一个包含一些字段的数据透视表。一个字段被添加为面向行。其余的是计算的数据字段。一切正常,数据添加正常。只有一个问题。计算的数据字段也作为行添加,但我希望将它们作为列。在Excel中,手动操作意味着将值从行拖到列。但是,我如何实现相同的编程?Excel互操作和DataField方向

我的代码:

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"; 
+0

你怎么mannage来解决这个问题?你能澄清一下吗? 提前谢谢! –

回答

4

你可能已经知道这一招...

当你知道该怎么做,直接在Excel中的东西,你希望通过编程实现同样的,你可以做一个宏记录器的良好用法(在开发人员工具中,请参阅第一张截图)。之后,您必须使用interop Excel将VBA宏转换为C#,但是如果您知道一点VB并不难。

How to find the macro recorder

那么对于你的问题我录拖动和列字段拖放到行部分的动作。由于宏记录,似乎你可以通过捡起目标场对象并改变其属性来实现定位位置

The drag and drop action

The recorded macro

+0

谢谢!很有用。我根本不使用Excel,所以这是一个很好的提示! – Lobuno