Bora.Ozgur
Bora.Ozgur

Reputation: 65

How to use mutliple colors in same cell in excel with C#

I need to use multiple colors in one excel cell but the code below works only last condition.

show image

I want like: grren-red-green-red-green-red

It works like: green-green-green-green-green-red

        List<string> myTexts = new List<string>
        {
            "aaaaaaaaaaaaaaaaa",  // green expected
            "bbbbbbbbbbbbbbbbb",  // red expected
            "ccccccccccccccccc",  // green expected
            "ddddddddddddddddd",  // red expected
            "eeeeeeeeeeeeeeeee",  // green expected
            "fffffffffffffffff"   // red expected
        };


        var startIndex = 1;
        for (int i = 0; i < liste.Count; i++)
        {
            cell.Value2 += myTexts[i];

            if (i%2 == 0)
            {
                cell.Characters(startIndex, myTexts[i].Length).Font.Color= Color.Green;
            }
            else
            {
                cell.Characters(startIndex, myTexts[i].Length).Font.Color = Color.Red;
            }

            startIndex += myTexts[i].Length;
        }

Upvotes: 1

Views: 113

Answers (1)

Marinus Pfund
Marinus Pfund

Reputation: 239

it should work if you set the cell.value2 text outside the loop to the complete string and manipulate the style afterwards:

        cell.Value2 = string.Join("", myTexts);
        var startIndex = 1;
        for (int i = 0; i < myTexts.Count; i++)
        {
            if (i % 2 == 0)
            {
                cell.Characters[startIndex, myTexts[i].Length].Font.Color = Color.Green;
            }
            else
            {
                cell.Characters[startIndex, myTexts[i].Length].Font.Color = Color.Red;
            }

            startIndex += myTexts[i].Length;
        }

Upvotes: 1

Related Questions