c# excel how to change a color of a particular row
40,702
Solution 1
Give this a shot, I have tested it and it works:
Excel.Application application = new Excel.Application();
Excel.Workbook workbook = application.Workbooks.Open(@"C:\Test\Whatever.xlsx");
Excel.Worksheet worksheet = workbook.ActiveSheet;
Excel.Range usedRange = worksheet.UsedRange;
Excel.Range rows = usedRange.Rows;
int count = 0;
foreach (Excel.Range row in rows)
{
if (count > 0)
{
Excel.Range firstCell = row.Cells[1];
string firstCellValue = firstCell.Value as String;
if (!string.IsNullOrEmpty(firstCellValue))
{
row.Interior.Color = System.Drawing.Color.Red;
}
}
count++;
}
workbook.Save();
workbook.Close();
application.Quit();
Marshal.ReleaseComObject(application);
Solution 2
Excel.Application xlAppToExport = new Excel.Application();
xlAppToExport.Workbooks.Add("");
Excel.Worksheet xlWorkSheetToExport = default(Excel.Worksheet);
xlWorkSheetToExport = (Excel.Worksheet)xlAppToExport.Sheets["Sheet1"];
xlWorkSheetToExport.Range["A5:F5"].EntireRow.Interior.Color = System.Drawing.Color.Gray;
Author by
Uni Le
Updated on November 11, 2020Comments
-
Uni Le over 3 years
I want to ask you guys, how to change color of a row to red in Excel table if the cell 1 isn't null.
XX YY ZZ ----------------- aa bb cc aa1 bb1 cc1 aa2 cc2 aa3 bb3 cc3 aa4
Excel.Application xlApp; Excel. Workbook xlWorkBook; Excel.Worksheet xlWorkSheet;
I'm very thankfull
-
Uni Le over 11 yearsI have got Error here: string firstCellValue = firstCell.Value; RuntimeBinderException: can't convert from double to string
-
Uni Le over 11 years1 question more, it has changed the color of my header too, what should i do?
-
Suren over 6 yearsIt is better if you can explain how this solves the problem.