Google Groups no longer supports new Usenet posts or subscriptions. Historical content remains viewable.
Dismiss

Mapping colors accurately C# to Excel

24 views
Skip to first unread message

Andrew Wiles

unread,
Sep 8, 2007, 5:32:00 AM9/8/07
to
If my understanding is correct Excel only supports a pallette of 56 colors.
If you try to set the background color of a cell to a color that is not
within the pallete the color rendered is usually "almost, but not entirely"
unlike the color requested.

((Excel.Range)sheet.Cells[row, column]).Interior.Color =
m_backgroundColor.ToArgb();

However features such as the conditional formatting options seem to be able
to render colors on smooth scales without impacting the standard color
pallette.

Is there any way to manipulate the color attributes using accurate color
mapping?

Andrew Wiles

unread,
Oct 1, 2007, 11:16:01 AM10/1/07
to
I eventually discovered that Office colors are stored in GBR format rather
than RGB. The Color.ToArgB function is therefore inappropriate.

The following function returns a valid Office color from a .Net color.

/// <summary>
/// Returns an Excel color from a .Net color
/// </summary>
/// <param name="netColor">Color</param>
/// <returns>int</returns>
public static int GetExcelColor(Color netColor)
{
string hexVal = netColor.B.ToString("x").PadLeft(2, '0') +
netColor.G.ToString("x").PadLeft(2, '0') +
netColor.R.ToString("x").PadLeft(2, '0');
return int.Parse(hexVal,
System.Globalization.NumberStyles.HexNumber);
}

There may of course be a more elegant way to handle this...

0 new messages