We're sorry Aspose doesn't work properply without JavaScript enabled.

Free Support Forum - aspose.com

Set background color of cells in Excel worksheet

I’d like to set the background color of cells with the a specific value to light gray. I can’t get this code to work:

        var maxRange = worksheet.Cells.MaxDisplayRange;
        var area = new CellArea { StartRow = maxRange.FirstRow, StartColumn = maxRange.FirstColumn, EndRow = maxRange.RowCount, EndColumn = maxRange.ColumnCount };
        var opts = new FindOptions {LookInType = LookInType.OriginalValues, LookAtType = LookAtType.EntireContent};
        opts.SetRange(area);

        Cell cell = null;
        do
        {
            cell = worksheet.Cells.Find("OPEN", cell, opts);
            if (cell == null)
                break;

            var style = cell.GetStyle();
            style.BackgroundColor = Color.LightGray;
            style.Pattern = BackgroundType.Solid;
            cell.SetStyle(style);

        } while (true);

What am I doing wrong?
Thanks in advance.

@mortenma,

You may please use style.ForegroundColor property to set the specific values gray in your sample code as follows:

style.ForegroundColor = Color.LightGray;

This behaviour is implemented similar to MS Excel. You might be mixing the two things foreground and background. You are taking foreground color as font text color or something like that, that is not like it. And, you are thinking of background color as cell shading color. For your info, Foreground color is the cell’s outline color and Background color is the back color of the cell actually. But, if you want to set a solid shading color for cells, you should use Foreground color with Solid pattern type. There is no need to use Background color then.

Thanks @ahsaniqbalsidiqui. That did trick. And thanks for the explanation.

@mortenma,

Good to know that your issue is sorted out by the suggested line of code. Feel free to contact us any time if you need further help or have some other issue or queries, we will be happy to assist you soon.