'how to get cell background color of excel using C#?
I want to retrieve the background color of cell of excel using c# but I just can't find a way to do it
which library shall I use ?
microsoft.office.tools.excel.workbook.aspxormicrosoft.office.interop.excel? what's the differents?I have tried following code but get no luck:
using Excel = Microsoft.Office.Interop.Excel; private void button1_Click(object sender, EventArgs e) { ofd.Filter = "xlsx|*.xlsx|xls|*.xls"; if(ofd.ShowDialog() == DialogResult.OK) { textBox2.Text = ofd.FileName; Excel.Application excel = new Excel.Application(); Excel.Workbook wb = excel.Workbooks.Open(textBox2.Text); Excel.Worksheet ws = wb.Sheets[1]; Excel.Range xlRange = ws.Cells[0, 0]; Debug.WriteLine("===" + xlRange.Interior.Color); } }
Solution 1:[1]
Easiest solution what-so-ever :
private void Get_Colors()
{
Excel.Workbook excel = Globals.ThisAddIn.Application.ActiveWorkbook;
Excel.Worksheet sheet = null;
Excel.Range ran = sheet.UsedRange;
for (int x = 1; x <= ran.Rows.Count; x++)
{
for (int y = 1; y <= ran.Columns.Count; y++)
{
string CellColor = sheet.Cells[x, y].Interior.Color.ToString(); //Here I go double value which is converted to string.
if (sheet.Cells[x, y].Value != null && (CellColor == Color.Transparent.ToArgb().ToString() || **CellColor == Excel.XlRgbColor.rgbGold.GetHashCode().ToString()**))
{
sheet.Cells[x, y].Interior.Color = Color.Transparent;
}
}
}
}
Solution 2:[2]
Here's an answer that uses closed.xml. It's open-source and works with modern Excel sheets.
IXLWorkbook wb = new XLWorkbook("C:\File_path_to_excel_file"); // Replace with your file path
IXLWorksheet ws = wb.Worksheet("SheetName") // Put your sheet name here
int backgroundColor = ws.Cell(rowIndex, colIndex).Style.Fill.BackgroundColor.Color.ToArgb(); // Gives the Argb values for the cell's background. Replace rowIndex and colIndex with the index numbers of the cell you want to check
Typically an uncolored cell's Argb color is 16777215.
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Christopher H. |
| Solution 2 | Unknown |
