简体   繁体   中英

c# excel write text with multicolor into the same cell

I want to write text into a excel cell with the diffrent conditions. For example if the selected value is red excel cell text might be red.I am using enum to define color which name is ExcelColorType But it doesn't work. What am i missing?

There is a some source code below.

private static void ExcelSatirGuncelle(Worksheet worksheet, string message, int rowNumber, ExcelColorType colorType)
{
    var cell = worksheet.Cells[rowNumber, 7];

    string values = cell.Value2;

    if (string.IsNullOrEmpty(values))
        values = "";        

    cell.Font.Bold = true;
    cell.ColumnWidth = 200;
    cell.Value2 += message + Environment.NewLine;

    cell.Characters(values.Length, message.Length).Font.Color = colorType== ExcelColorType.Yesil ? Color.Green : Color.Red;

    worksheet.Cells.VerticalAlignment = XlVAlign.xlVAlignCenter;
    worksheet.Cells.HorizontalAlignment = XlHAlign.xlHAlignLeft;
}

Actually this code is working in the runtime. But All text is being green. I have several if condition color might be Color.Red but all text being green.

Try the following.

            ((Excel.Range)worksheet.Cells[rowNumber, 7]).Value = message;
            Range cell = (Excel.Range)worksheet.Cells[rowNumber, 7];

            if (colorType.Equals("Green"))
            {
                cell.Characters[0, message.Length].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Green);
            }
            else
            {
                cell.Characters[0, message.Length].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);
            }

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