简体   繁体   中英

How to render the Excel cells font color with C#?

I need to render a color in Excel,when the cells content is equal to "true",the font color is green!When the font content is equal to "false",the color is red.This is my code:

private void colorRender(Worksheet workSheet)
    {
      for(int i=0;i<workSheet.Rows.Count;i++)
      {
        for(int j=0;j<workSheet.Columns.Count;j++)
        {
          if(workSheet.Columns.Name=="校验结果")
          {
            if(workSheet.Cells[i,j].ToString()=="false")
            {
              //if the cells was equal to false,set the font color red,others green. 
              //Microsoft.Office.Interop.Excel.Range range=Microsoft.Office.Interop.Excel.Worksheets.
            }
          }
        }
      }
    }

When i write there and i encounter a problem:the worksheet do not contain a get_range funcion.

You have to cast the Cell object you want to be a range, then try to set font style.

if (workSheet.Columns.Name == "校验结果")
{
    Excel.Range range = workSheet.Cells[i, j] as Excel.Range;
    if (range.Value2.ToString() == "false")
    {
        range.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
    }
    else
    {
        range.Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM