Exemplo n.º 1
0
        /// <summary>
        /// Resolve the name references and other formulas contained in a formula.
        /// </summary>
        /// <param name="calculatedFields">The list of calculated fields in the pivot table.</param>
        /// <param name="totalsCalculator">The function helper calculator.</param>
        /// <param name="pivotTable">The pivot table the fields are on.</param>
        public static void ConfigureCalculatedFields(IEnumerable <CacheFieldNode> calculatedFields, TotalsFunctionHelper totalsCalculator, ExcelPivotTable pivotTable)
        {
            // Add all of the cache field names to the calculation helper.
            var cacheFieldNames = new HashSet <string>(pivotTable.CacheDefinition.CacheFields.Select(c => c.Name));

            totalsCalculator.AddNames(cacheFieldNames);

            // Resolve any calclulated fields that may be referencing each other to forumlas composed of regular ol' cache fields.
            foreach (var calculatedField in calculatedFields)
            {
                var resolvedFormulaTokens = PivotTableDataManager.ResolveFormulaReferences(calculatedField.Formula, totalsCalculator, calculatedFields);
                foreach (var token in resolvedFormulaTokens.Where(t => t.TokenType == TokenType.NameValue))
                {
                    if (!calculatedField.ReferencedCacheFieldsToIndex.ContainsKey(token.Value))
                    {
                        var referencedFieldIndex = pivotTable.CacheDefinition.GetCacheFieldIndex(token.Value);
                        calculatedField.ReferencedCacheFieldsToIndex.Add(token.Value, referencedFieldIndex);
                    }
                }
                // Reconstruct the formula and wrap all field names in single ticks.
                string resolvedFormula = string.Empty;
                foreach (var token in resolvedFormulaTokens)
                {
                    string tokenValue = token.Value;
                    if (token.TokenType == TokenType.NameValue)
                    {
                        tokenValue = $"'{tokenValue}'";
                    }
                    resolvedFormula += tokenValue;
                }
                calculatedField.ResolvedFormula = resolvedFormula;
            }
        }