Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I change color of text in a cell of MS Excel?

Tags:

c#

excel

I am using Microsoft.Office.Interop.Excel library.

I have a cell with values "Green Red". What I want is pretty simple. I want to insert "Green" text to be green and "Red" to be red, like that:

enter image description here

I am using this code to insert data in cell:

Excel.Application excelApp = new Excel.Application();
excelApp.Workbooks.Add();
// single worksheet
Excel._Worksheet workSheet = excelApp.ActiveSheet;

for (int startIndex = 0; startIndex < 10; startIndex++)
{
    workSheet.Cells[1, (startIndex + 1)] ="Green" + " Red";
}

How to do it?

I've tried this approach, but I do not know what [RangeObject] is:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

like image 958
StepUp Avatar asked Apr 07 '16 11:04

StepUp


1 Answers

Try:

workSheet.Cells[1, (i + 1)].Characters[start_pos, len].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

where start_pos and len is the part of the string where to apply color.

Your use case example:

    Application excelApp = new Application();
    excelApp.Workbooks.Add();
    // single worksheet
    _Worksheet workSheet = excelApp.ActiveSheet;

    string Green = "Green";
    string Red = "Red";
    for (int start = 0; start < 10; start++)
    {
        Range ColorMeMine = workSheet.Cells[1, (start + 1)];
        ColorMeMine.Value = string.Format("{0} {1}", Green, Red);
        ColorMeMine.Characters[0, Green.Length].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
        ColorMeMine.Characters[Green.Length + 1, Green.Length + 1 + Red.Length].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
    }
like image 70
Adam Calvet Bohl Avatar answered Sep 22 '22 02:09

Adam Calvet Bohl