Changing an Excel cell's backcolor using hex results in Excel displaying completely different color in the spreadsheet

后端 未结 7 1892
灰色年华
灰色年华 2021-02-07 13:27

So I am setting an Excel cell\'s Interior Color to a certain value, like below:

worksheet.Cells[1, 1].Interior.Color = 0xF1DCDB;

However, when

相关标签:
7条回答
  • 2021-02-07 13:41

    Please note that this is not a bug!Red starts from the lower bit and Green is in the middle and Blue takes the highest bits

    B G R
    00000000 00000000 00000000

    The calculation is: (65536 * Blue) + (256 * Green) + (Red)

    Thank you.

    0 讨论(0)
  • 2021-02-07 13:41

    This is background information that may explain the answers.

    If with HTML you specify colour #FF9900 you will get what Excel calls Light orange. If you specify colour #003366 you will get what Excel calls Dark teal. But if you want Light orange or Dark teal with vba you must specify &H0099FF and &H663300.

    That is, although the vba function is RGB(&Hrr, &Hgg, &Hbb) the number it generates is &Hbbggrr because that is what the Excel display engine wants.

    I would guess the person who coded the Excel Interop was unaware that Excel uses non standard numbers to specify colours.

    0 讨论(0)
  • 2021-02-07 13:46

    Just wanted to post my code, too. Since there was no copy&paste solution for me. Based on Sandesh 's code:

    private void ColorMe(Color thisColor){
    rng = xlApp.ActiveCell;
    Color mycolour = ColorTranslator.FromHtml("#" + thisColor.Name.Substring(2, 6));
    rng.Interior.Color = Color.FromArgb(mycolour.R, mycolour.G, mycolour.B);
    }
    
    0 讨论(0)
  • 2021-02-07 13:49

    The RGB colour alone can be parsed from an HTML hex string:

    Color colour = ColorTranslator.FromHtml("#E7EFF2");
    

    If you have a separate alpha value you can then apply this (docs):

    Color colour = ColorTranslator.FromHtml("#E7EFF2");
    Color transparent = Color.FromArgb(128, colour);
    
    0 讨论(0)
  • 2021-02-07 13:53

    I finally figured it out, after lots of tests, and it was something really simple. Apparently, Excel's Interop library has a bug and is reversing the Red and Blue values, so instead of passing it a hex of RGB, I need to pass BGR, and suddenly the colors work just fine. I'm amazed that this bug isn't documented anywhere else on the internet.

    So if anyone else ever runs into this problem, simply pass Excel values in BGR values. (Or if using Color.FromArgb(), pass in Color.FromArgb(B, G, R))

    0 讨论(0)
  • 2021-02-07 13:55

    You need to convert the color from hex to Excel's color system as follows:

    ColorConverter cc = new ColorConverter();
    worksheet.Cells[1, 1].Interior.Color = ColorTranslator.ToOle((Color)cc.ConvertFromString("#F1DCDB"));
    

    It's not really a bug, since Excel's color system has always been this way. It's just one more thing that makes C# - Excel interop a pain.

    0 讨论(0)
提交回复
热议问题