How to convert Tint value with base color to System.Drawing.Color using OpenXml Library in C#?

Pritam Adak 0 Reputation points
2024-05-17T06:51:04.5666667+00:00

Using OpenXml library i want to get the cell background color. when i tried with the below code i did not get the actual color of cell background. Please help me on this.

 private static BooleanResult<System.Drawing.Color> PrintColorType(SpreadsheetDocument sd, DocumentFormat.OpenXml.Spreadsheet.ColorType ct)
{
    try
    {
        System.Drawing.Color color = System.Drawing.Color.White;
        if (ct.Auto != null)
        {
            color = System.Drawing.Color.White;
        }

        if (ct.Rgb != null)
        {
            color = ColorsHelper.HtmlRgbToColor(ct.Rgb.Value);
        }
        if (ct.Theme != null && ct.Tint != null)
        {
            DocumentFormat.OpenXml.Drawing.Color2Type c2t = (DocumentFormat.OpenXml.Drawing.Color2Type)sd.WorkbookPart
                .ThemePart.Theme.ThemeElements.ColorScheme.ChildElements[(int)ct.Theme.Value];
            color = ParseRgbColortint(ct.Tint.Value, ColorsHelper.HtmlRgbToColor(c2t.RgbColorModelHex.Val));
        }
        return BooleanResult<System.Drawing.Color>.SuccessResult(color);
    }
    catch (ArgumentException ex)
    {
        return BooleanResult<System.Drawing.Color>.FailResult(
            $"PrintColorType: ArgumentException: {ex.GetFullMessage()}");
    }
    catch (InvalidOperationException ex)
    {
        return BooleanResult<System.Drawing.Color>.FailResult(
            $"PrintColorType: InvalidOperationException: {ex.GetFullMessage()}");
    }
    catch (Exception ex)
    {
        return BooleanResult<System.Drawing.Color>.FailResult(
            $"PrintColorType: Exception: {ex.GetFullMessage()}");
    }
}

private static int TintComponent(int component, double tint)
{
    return Round(component * (1 - tint) + 255 * tint);
}
private static int Round(double value)
{
    return (int)Math.Round(value);
}
private static System.Drawing.Color ParseRgbColortint(double tint1, System.Drawing.Color baseColor)
{
    double tint = Math.Max(0, Math.Min(1, tint1)); // Ensure tint is between 0 and 1
    int tintedRed = TintComponent(baseColor.R, tint);
    int tintedGreen = TintComponent(baseColor.G, tint);
    int tintedBlue = TintComponent(baseColor.B, tint);

    return System.Drawing.Color.FromArgb(tintedRed, tintedGreen, tintedBlue);
}
Excel
Excel
A family of Microsoft spreadsheet software with tools for analyzing, charting, and communicating data.
1,571 questions
Office Development
Office Development
Office: A suite of Microsoft productivity software that supports common business tasks, including word processing, email, presentations, and data management and analysis.Development: The process of researching, productizing, and refining new or existing technologies.
3,622 questions
0 comments No comments
{count} votes