简体   繁体   English

在 C# 代码中的数据透视表 CalculatedField 中使用 excel 公式

[英]Using excel formula in Pivot table CalculatedField in C# code

I need to generate a pivot table from an excel file using C# code.我需要使用 C# 代码从 excel 文件生成数据透视表。 In excel, some calculated fields are currently used to generate a pivot table and I would need to convert those formulas from excel to C# code.在 excel 中,一些计算字段当前用于生成数据透视表,我需要将这些公式从 excel 转换为 C# 代码。 Excel formula: Excel公式:

=IF(CountA<>0;CountA/CountB;"0")

This formula is used in a calculated field used in Pivot table.此公式用于数据透视表中使用的计算字段。 Here CountA and CountB columns exist in excel.这里 CountA 和 CountB 列存在于 excel 中。

I tried the following code but it is throwing an interop exception :我尝试了以下代码,但它引发了interop exception

oPivotTable.AddDataField(oPivotTable.CalculatedFields()
    .Add("RateA", "= IF('CountA' != 0;'CountA' / 'CountB';0)", true),
  " RateA", Excel.XlConsolidationFunction.xlSum);

Although some simple formulas are working in calculatedFields.尽管一些简单的公式在 calculatedFields 中起作用。

Try the below code:试试下面的代码:

pivotTable.CalculatedFields().Add("RateA",
                                  "= IF('CountA' != 0,'CountA' / 'CountB',0)", true);

pivotTable.PivotFields("RateA").Orientation = MSExcel.XlPivotFieldOrientation.xlDataField;

pivotTable.PivotFields("Sum of " + drFormula["CustomList"].ToString()).Caption = " RateA";

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM