我正在使用此计算字段生成电子表格:
pivotTable.AddCalculatedField("Average Price", "=TotalPrice/TotalQty", true);
它大部分时间都像魅力一样,但偶尔有0值,因此产生一个" #Div / 0!",例如显示的第二个和最后一个项目这里:
我该如何防止这种情况?
以下是完整的数据透视表创建代码,以获取更多上下文:
private void PopulatePivotTableSheet()
{
int DESCRIPTION_COLUMN = 1;
int MONTHYR_COLUMN = 3;
int TOTALQTY_COLUMN = 4;
int TOTALPRICE_COLUMN = 5;
int PERCENTOFTOTAL_COLUMN = 7;
int MONTHLY_PERCENTAGE_COLUMN = 8;
int AVGPRICE_COLUMN = 10;
int COLUMNS_IN_DATA_SHEET = 11;
int HEADER_ROW = 8;
AddPreDataSectionToPivotTableSheet();
PivotTableCollection pivotTables = pivotTableSheet.PivotTables;
int colcount = COLUMNS_IN_DATA_SHEET;
string lastColAsStr = ReportRunnerConstsAndUtils.GetExcelColumnName(colcount);
int rowcount = sourceDataSheet.Cells.Rows.Count;
string sourceDataArg = string.Format("sourceDataSheet!A1:{0}{1}", lastColAsStr, rowcount);
int index = pivotTableSheet.PivotTables.Add(sourceDataArg, "A6", "PivotTableSheet");
PivotTable pivotTable = pivotTables[index];
pivotTable.RowGrand = true;
pivotTable.ColumnGrand = true;
pivotTable.DisplayNullString = true;
pivotTable.NullString = "0";
pivotTable.AddFieldToArea(PivotFieldType.Row, DESCRIPTION_COLUMN);
pivotTable.RowHeaderCaption = "Description";
pivotTable.AddFieldToArea(PivotFieldType.Column, MONTHYR_COLUMN);
pivotTable.ColumnHeaderCaption = "Months";
pivotTable.AddFieldToArea(PivotFieldType.Data, TOTALQTY_COLUMN);
pivotTable.DataFields[0].DisplayName = "Total Packages";
pivotTable.AddFieldToArea(PivotFieldType.Data, TOTALPRICE_COLUMN);
pivotTable.DataFields[1].DisplayName = "Total Purchases";
pivotTable.AddCalculatedField("Average Price", "=TotalPrice/TotalQty", true);
pivotTable.AddCalculatedField("PercentOfTotal", "=TotalPrice", true);
pivotTable.DataFields[3].DisplayName = "Percentage of Total";
pivotTable.DataFields[3].DataDisplayFormat = PivotFieldDataDisplayFormat.PercentageOfColumn;
pivotTable.RowFields[0].IsAutoSubtotals = false;
PivotField field = pivotTable.RowFields[0];
field.IsAutoSort = true;
field.IsAscendSort = false;
field.AutoSortField = 1;
pivotTable.PivotTableStyleType = PivotTableStyleType.PivotTableStyleLight16;
pivotTable.RefreshDataFlag = true;
pivotTable.RefreshData();
pivotTable.CalculateData();
pivotTable.RefreshDataFlag = false;
List<String> contractItemDescs = GetContractItemDescriptions();
ColorizeContractItemBlocks(contractItemDescs);
HideItemsWithFewerThan1PercentOfSales();
FreezePanePivotTable(HEADER_ROW, 2);
FormatPivotTableNumbers();
Style style = workBook.CreateStyle();
style.Font.Name = "Calibri";
style.Font.Size = 12;
pivotTable.FormatAll(style);
sourceDataSheet.IsVisible = false;
}
答案 0 :(得分:1)
在除以之前检查TotalQty
是否为零:
"=IF(TotalQty<>0,TotalPrice/TotalQty,0)"
第三个参数是TotalQty
为零时显示的值。
答案 1 :(得分:1)
您也可以尝试:
IFERROR(TotalPrice/TotalQty,"")
如果您愿意,双引号可以为零。
答案 2 :(得分:1)
只需使用
if(ISBLANK((单元格范围),&#34;&#34;,此处的功能)
&#34;&#34;如果单元格的范围不包含任何内容,则用于显示为空单元格(空白,就好像此处没有任何内容一样)。否则,如果在单元格中找到任何值,则将运行您的函数