public static void GetAndOrSetErrorStyleID(SpreadsheetDocument workdocument, Worksheet worksheet, Cell currentCell) { WorkbookStylesPart stylesPart = workdocument.WorkbookPart.WorkbookStylesPart; uint fillId = GetOrSetErrorFillID(workdocument); uint styleId = currentCell.StyleIndex ?? 0; CellFormats cellFormats = stylesPart.Stylesheet.CellFormats; CellFormat currentCellCellFormat = cellFormats.Descendants <CellFormat>().ElementAt((int)styleId); bool cellFormatComparation = true; uint checkedStyleIndex = 0; //iterate over all cellFormat of the page foreach (CellFormat cfItem in cellFormats) { checkedStyleIndex++; cellFormatComparation = true; //iterate over all attributes of the current cellFormat to check if all are the same foreach (var item in cfItem.GetAttributes()) { bool check = false; try { check = Equals(currentCellCellFormat.GetAttribute(item.LocalName, item.NamespaceUri), item); } catch (KeyNotFoundException) { check = false; break; } if (!check) // { cellFormatComparation = false; break; } } if (cellFormatComparation) { styleId = checkedStyleIndex; break; } } if (cellFormatComparation) { if (currentCellCellFormat.FillId != fillId) { CellFormat currentCellNewFormat = (CellFormat)currentCellCellFormat.CloneNode(true); currentCellNewFormat.FillId = fillId; cellFormats.AppendChild(currentCellNewFormat); cellFormats.Count++; } } else { cellFormats.AppendChild(new CellFormat() { BorderId = DefaultStyle, FillId = ErrorStyleFillId, FontId = DefaultStyle, NumberFormatId = DefaultStyle }); cellFormats.Count++; } styleId = (uint)cellFormats.Descendants <CellFormat>().Count(); currentCell.StyleIndex = styleId - 1; worksheet.Save(); }