OpenXML - after editing xlsx Excel detects errors in the file

I have an xlsx file with a pivot table and some filter (rotation field), I'm trying to use OpenXML for:

  • Open file
  • Change the rotation field setting
  • Save file

I use this simple (and ugly) code to do the job:

OpenSettings settings = new OpenSettings()
{
    MarkupCompatibilityProcessSettings = new MarkupCompatibilityProcessSettings(MarkupCompatibilityProcessMode.ProcessAllParts, FileFormatVersions.Office2010)
};

SpreadsheetDocument spd = SpreadsheetDocument.Open(pathToFile, true, settings);
var pivotTableCacheDefinitionParts = spd.WorkbookPart.PivotTableCacheDefinitionParts;

foreach (PivotTableCacheDefinitionPart item in pivotTableCacheDefinitionParts)
{
    var pivotCacheDefinition = item.PivotCacheDefinition;

    var d = pivotCacheDefinition.CacheFields.Where(x => (x as CacheField).Caption == "Some filter from Excel");

    foreach(var item2 in d)
    {
        if (item2.InnerXml.Contains("Some filter value"))
        {
            var a1 = item2.InnerXml.Replace("><", ">\n<").Split('\n');
            var a2 = a1.Where(x => !x.Contains("Some filter value"));
            string a3 = "";

            foreach (var item3 in a2)
            {
                a3 += item3;
            }
            a3=a3.Replace("count=\"2\"","count=\"1\"");//There are two values to choose from currently

            item2.InnerXml = a3;
        }
    }
}

After saving my document with:

spd.WorkbookPart.Workbook.Save();
spd.Close();

Excel claim file is damaged and will try to repair it ... I tried to use other libraries, but:

ClosedXML - it does not see any data in pivot tables (perhaps because OLAP is used as a data source? I don't know)

ExcelDataReader - doesn't seem to support pivot tables or only partially supports them

EPPlus (- - xlsx) - , , ( )

MS.Office.Interop.Excel - ( ), ,

?

+4

All Articles