How to read the cell colour from Excel using C#

Kalpana 291 Reputation points
2022-03-25T07:44:13.447+00:00

Hi

What library ( free ) that I can use to read the cell colour of an Excel worksheet ?

I would need to read the cell colour code from one column and then check other columns if they have the same corresponding cell colour and some other matching variables ?

At the moment, I am just using oledb and it's just returning data as plain text.

Developer technologies C#
0 comments No comments
{count} votes

3 answers

Sort by: Most helpful
  1. Sreeju Nair 12,666 Reputation points
    2022-03-25T07:57:37.24+00:00

    You can use EPPlus Library, which is free for personal use.

    https://www.epplussoftware.com/en

    You may read about the licensing here more: https://www.epplussoftware.com/en/LicenseOverview/, go to the last section in the page that speaks about non commercial license.

    Once you add EPPlus to your project, you can read the cell background color as follows.

    var bgColor = sheet.Cells[rowId, colId].Style.Fill.BackgroundColor;
    
    //To set the back ground color you may use
    
    sheet.Cells[rowId, colId].Style.Fill.SetCellsColor(Color.Blue);
    

    Hope this helps


  2. Kalpana 291 Reputation points
    2022-03-25T09:10:22.267+00:00

    What about OpenXML or ClosedXML?

    The user that is will be working on the web application would have Excel installed in the machine.

    0 comments No comments

  3. Castorix31 90,681 Reputation points
    2022-03-25T14:31:17.38+00:00

    You can get it with OpenXML and PatternFill Class
    but it is not easy
    You can find samples like in this thread
    (you must add tests
    if (fill.PatternFill.BackgroundColor != null)
    and
    if (fill.PatternFill.ForegroundColor != null)
    or it will crash if they are null
    )

    From my tests, the Foreground is in fact the color of the brush to fill the cell
    I get for example, for a cell where I changed the background color to Red or Yellow :

                        // Red  
                        // BackgroundColor.Indexed.Value 64  
                        // ForegroundColor.Rgb.Value FFFF0000  
    
                        // Yellow  
                        // BackgroundColor.Indexed.Value 64  
                        // ForegroundColor.Rgb.Value FFFFFF00  
    
    0 comments No comments

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.