c# excel how to change a color of a particular row

后端 未结 2 820
一整个雨季
一整个雨季 2020-12-11 02:59

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         


        
2条回答
  •  一个人的身影
    2020-12-11 03:47

    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);
    

提交回复
热议问题