I have a class Comparer
, which defines the following:
// partial Comparer code
public class Comparer
{
private readonly Color colorWarning = Color.Red;
private readonly string SPREADSHEET_RED_WARNING_STYLE = "red warning style";
private OfficeOpenXml.Style.XmlAccess.ExcelNamedStyle redWarningStyle;
}
This class has a method prepareSpreadsheet
:
private void prepareSpreadsheet()
{
// spreadsheet styles
redWarningStyle = spreadsheet.Workbook.Styles.CreateNamedStyle(SPREADSHEET_RED_WARNING_STYLE);
redWarningStyle.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
redWarningStyle.Style.Fill.BackgroundColor.SetColor(colorWarning);
redWarningStyle.Style.Font.Color.SetColor(Color.Black)
}
If the spreadsheet file already contains such a named style, an exception is thrown. Can Epplus programatically check if a certain named style already exists in the spreadsheet, and remove it if it does?
I have managed to get it working, but not sure if it is the best solution. It does not remove them, only adds if it finds a style with an existing name (cannot guarantee it has the same style):
// retrieve a list of styles from the spreadsheet
List<OfficeOpenXml.Style.XmlAccess.ExcelNamedStyleXml> spreadsheetNamedStyles = spreadsheet.Workbook.Styles.NamedStyles.ToList();
// check if it already exists before attempting to add it
if (spreadsheetNamedStyles.FirstOrDefault(namedStyle => namedStyle.Name.Equals(SPREADSHEET_RED_WARNING_STYLE)) == null)
{
redWarningStyle = spreadsheet.Workbook.Styles.CreateNamedStyle(SPREADSHEET_RED_WARNING_STYLE);
redWarningStyle.Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
redWarningStyle.Style.Fill.BackgroundColor.SetColor(colorWarning);
redWarningStyle.Style.Font.Color.SetColor(Color.Black);
}