{"record":{"id":"6fa3322c803cc367","repo":"iOfficeAI/OfficeCLI","slug":"pivotcachedefinition-is-missing-cachefields","errorCode":null,"errorMessage":"pivotCacheDefinition is missing <cacheFields>","messagePattern":"pivotCacheDefinition is missing <cacheFields>","errorType":"exception","errorClass":"InvalidOperationException","httpStatus":null,"severity":"error","filePath":"src/officecli/Core/PivotTableHelper.Definition.cs","lineNumber":1504,"sourceCode":"    // Do NOT emit a <x:calculatedFields> block on pivotTableDefinition —\n    // that element is NOT a valid child there (ECMA-376 places it only\n    // under pivotCacheDefinition, and Excel rejects the file as schema-\n    // invalid). The cacheField/@formula attribute alone fully expresses\n    // the calculated field; Excel rebuilds the column live on open.\n    //\n    // No records are written for calculated fields (databaseField=\"0\"),\n    // matching the date-group-derived pattern — Excel computes the column\n    // live from the formula when the workbook opens.\n    internal static void ApplyCalculatedFields(\n        PivotCacheDefinition cacheDef,\n        PivotTableDefinition pivotDef,\n        Dictionary<string, string> properties)\n    {\n        var specs = ParseCalculatedFieldSpecs(properties);\n        if (specs.Count == 0) return;\n\n        var cacheFields = cacheDef.GetFirstChild<CacheFields>()\n            ?? throw new InvalidOperationException(\"pivotCacheDefinition is missing <cacheFields>\");\n        var pivotFields = pivotDef.PivotFields\n            ?? throw new InvalidOperationException(\"pivotTableDefinition is missing <pivotFields>\");\n\n        // Collect existing names (in both cacheFields and calculated specs)\n        // so we can reject duplicates cleanly.\n        var existingNames = new HashSet<string>(StringComparer.OrdinalIgnoreCase);\n        foreach (var cf in cacheFields.Elements<CacheField>())\n            if (!string.IsNullOrEmpty(cf.Name?.Value))\n                existingNames.Add(cf.Name!.Value!);\n\n        // Ensure <dataFields> exists so we can append to it.\n        var dataFields = pivotDef.DataFields;\n        if (dataFields == null)\n        {\n            dataFields = new DataFields { Count = 0u };\n            pivotDef.DataFields = dataFields;\n        }\n","sourceCodeStart":1486,"sourceCodeEnd":1522,"githubUrl":"https://github.com/iOfficeAI/OfficeCLI/blob/1ced45e900782c5083ed550ddf328ee974e425e7/src/officecli/Core/PivotTableHelper.Definition.cs#L1486-L1522","documentation":"InvalidOperationException thrown by ApplyCalculatedFields when the pivotCacheDefinition has no <cacheFields> child. Calculated fields are added both as a <cacheField> (for the formula/field metadata) and a <dataField>, so a missing <cacheFields> root means the cache definition is malformed/incomplete and the operation cannot proceed.","triggerScenarios":"Calling pivot-table calculated-field creation (ApplyCalculatedFields via the pivot create/Set path with a calculatedFields spec) on a pivot cache whose PivotCacheDefinition lacks a CacheFields element — e.g. a cache built from an empty/degenerate source or a corrupted definition.","commonSituations":"Adding a calculated field to a pivot whose cache was never populated (empty source range / no headers); a hand-built or corrupted cache definition missing <cacheFields>; operating before the cache was fully initialized.","solutions":["Ensure the pivot table's source cache has real <cacheFields> (i.e. the source range has headers/columns) before adding a calculated field.","Create/refresh the pivot cache against a populated source range first.","If the file is corrupted, rebuild the pivot cache (or the workbook) from valid source data."],"exampleFix":null,"handlingStrategy":"type-guard","validationCode":"var cacheFields = cacheDef.GetFirstChild<CacheFields>();\nif (cacheFields == null) { /* do not add calculated fields; rebuild/refresh the cache from a populated source first */ }","typeGuard":"static bool CacheHasFields(PivotCacheDefinition cd) => cd?.GetFirstChild<CacheFields>() != null;","tryCatchPattern":null,"preventionTips":["Build/refresh the pivot cache from a populated source (with headers) before adding calculated fields.","Check for <cacheFields> before calling ApplyCalculatedFields.","Rebuild corrupted caches from valid source data."],"tags":["pivot-table","excel","ooxml","invalid-operation","precondition","calculated-field","officecli"],"backgroundTag":null,"analyzedSha":"1ced45e900782c5083ed550ddf328ee974e425e7","analyzedAt":"2026-08-13T13:01:07.193Z","schemaVersion":2},"datasetVersion":"2026-08-13T14:17:21.547Z"}