c++excelcolorslibrariesfill

Xlnt library. Is there a way to store excel cell color information in rgb format?


I can't find any function which store cell color data in rgb format. I just simply want to get color from one cell and freely fill another cell with this color.

To fill cell I use this function,but can't find a way to store the color. cell.fill(xlnt::fill::solid(xlnt::rgb_color(242, 34, 15)));


Solution

  • Ultimately, the answer lies in just using cell.fill().pattern_fill().foreground().rgb(). That's the easiest way to retrieve the color. However, I also created the implementation you described just as an example.

    //This is what you asked for
    xlnt::rgb_color get_cell_color(const xlnt::cell &cell) {
        if (cell.fill().type() == xlnt::fill_type::pattern) {
            xlnt::pattern_fill pattern = cell.fill().pattern_fill();
            if (pattern.foreground().type() == xlnt::color_type::rgb) {
                return pattern.foreground().rgb();
            }
        }
        return xlnt::rgb_color(0, 0, 0); // Default to black if no color is found
    }
    
    //I took the function you used to fill, and I made it fit in a little bit better 
    void color_fill_cell(xlnt::cell &cell, const xlnt::rgb_color &rgb) {
        cell.fill(xlnt::fill::solid(rgb));
    }
    
    

    Now that we have those functions, we can implement them pretty easily:

    xlnt::worksheet ws = ; // Just plop your worksheet here
    
    xlnt::cell source_cell = ws.cell("A1"); //Obv A1 is a placeholder
    xlnt::rgb_color rgb = get_cell_color(source_cell);
    
    xlnt::cell target_cell = ws.cell("B1"); //placeholder again
    color_fill_cell(target_cell, rgb);