Syncfusion AI Assistant

How can I help you?

How to set a hex color value for a cell?

13 Nov 20255 minutes to read

XlsIO does not provide a direct API to assign a hex color string to a cell style. Convert the hex value to an RGB Color and then assign it to CellStyle.Color. The following example demonstrates this approach.

using (ExcelEngine excelEngine = new ExcelEngine())
{               
    IApplication application = excelEngine.Excel;                
    IWorkbook workbook = application.Workbooks.Create(1);               
    IWorksheet worksheet = workbook.Worksheets[0];

    // Set hex color
    worksheet["A1"].CellStyle.Color = HexToRgb("#FF0000");

    workbook.SaveAs("HexColor.xlsx");
    workbook.Close();
    excelEngine.Dispose();
}

public static Color HexToRgb(string hexColor)
{
    hexColor = hexColor.TrimStart('#');
    int hexValue = int.Parse(hexColor, System.Globalization.NumberStyles.HexNumber);
    Color rgbColor = Color.FromArgb(
        hexValue >> 16) & 0xFF,   // Red
        hexValue >> 8) & 0xFF,    // Green
        hexValue & 0xFF            // Blue
    );

    return rgbColor;
}
using (ExcelEngine excelEngine = new ExcelEngine())
{
    IApplication application = excelEngine.Excel;
    IWorkbook workbook = application.Workbooks.Create(1);
    IWorksheet worksheet = workbook.Worksheets[0];

    // Set hex color
    worksheet["A1"].CellStyle.Color = HexToRgb("#FF0000");

    workbook.SaveAs("HexColor.xlsx");
    workbook.Close();
    excelEngine.Dispose();
}

public static Color HexToRgb(string hexColor)
{
    hexColor = hexColor.TrimStart('#');
    int hexValue = int.Parse(hexColor, System.Globalization.NumberStyles.HexNumber);
    Color rgbColor = Color.FromArgb(
        (hexValue >> 16) & 0xFF,   // Red
        (hexValue >> 8) & 0xFF,    // Green
        hexValue & 0xFF            // Blue
    );

    return rgbColor;
}
Using excelEngine As New ExcelEngine()
    Dim application As IApplication = excelEngine.Excel
    Dim workbook As IWorkbook = application.Workbooks.Create(1)
    Dim worksheet As IWorksheet = workbook.Worksheets(0)

    ' Set hex color
    worksheet("A1").CellStyle.Color = HexToRgb("#FF0000")

    workbook.SaveAs("HexColor.xlsx")
    workbook.Close()
End Using

Public Function HexToRgb(hexColor As String) As Color
    hexColor = hexColor.TrimStart("#"c)
    Dim hexValue As Integer = Integer.Parse(hexColor, NumberStyles.HexNumber, CultureInfo.InvariantCulture)
    Dim rgbColor As Color = Color.FromArgb(
        (hexValue >> 16) And &HFF,  ' Red
        (hexValue >> 8) And &HFF,   ' Green
        hexValue And &HFF           ' Blue
    )
    Return rgbColor
End Function

See Also