Retrieving Themable Cell Color in RadSpreadProcessing
Environment
Version | Product | Author |
---|---|---|
2024.2.426 | RadSpreadProcessing | Desislava Yordanova |
Description
Let's import an Excel file with some cells formatted with color. Learn how to retrieve the cell color when the background color is set from MS Excel with a theme.
It is possible to set a Standard Color (e.g. Yellow) or a Theme Color (e.g. Dark Teal, Accent 1) to a cell:
Standard Color | Theme Color |
---|---|
The Yellow color will be fixed and after the changing the document's theme, it wouldn't change. However, the Dark Teal, Accent 1 color will be changed if another theme is selected:
This article demonstrates how to extract the color value from a cell when it is applied via a theme color.
Solution
To retrieve the cell color in RadSpreadProcessing, especially when the color is applied through the document theme, follow these steps:
- Import the Excel document using the appropriate format provider.
- Access the desired cell or range of cells.
- Check if the cell's fill is of type PatternFill.
- Retrieve the ThemableColor object from the
PatternFill
. - Use the GetActualValue method of the
ThemableColor
object, passing in the document's theme, to get the actual color value.
Here is a sample code snippet demonstrating these steps:
string filePath = "Book1.xlsx";
Workbook workbook = new Workbook();
IWorkbookFormatProvider formatProvider = new Telerik.Windows.Documents.Spreadsheet.FormatProviders.OpenXml.Xlsx.XlsxFormatProvider();
using (Stream input = new FileStream(filePath, FileMode.Open))
{
workbook = formatProvider.Import(input);
}
Worksheet worksheet = workbook.Worksheets.First();
CellSelection selection = worksheet.Cells[0,1];
PatternFill solidPatternFill = selection.GetFill().Value as PatternFill;
if (solidPatternFill != null)
{
PatternType type = solidPatternFill.PatternType;
ThemableColor patternColor = solidPatternFill.PatternColor;
Color color = patternColor.LocalValue;
ThemableColor bg = solidPatternFill.BackgroundColor;
Color bgcolor = bg.LocalValue;
Color actualColor = patternColor.GetActualValue(workbook.Theme);
// The actual color is the same as Accent1 color of the colorScheme
Debug.WriteLine("RGB: " + actualColor.R.ToString() + ", " + actualColor.G.ToString() + ", " + actualColor.B.ToString());
}
This approach ensures that even when a cell's color is derived from the document's theme, you can obtain the actual color value as displayed in the Excel file.