【问题标题】:c# excel write text with multicolor into the same cellc# excel将多色文本写入同一个单元格
【发布时间】:2019-11-27 23:42:23
【问题描述】:

我想将文本写入具有不同条件的 excel 单元格。例如,如果所选值是红色 excel 单元格文本可能是红色的。我正在使用枚举来定义颜色,名称为 ExcelColorType 但它不起作用。我错过了什么?

下面有一些源代码。

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

实际上这段代码在运行时工作。但是所有文本都是绿色的。我有几个 if 条件颜色可能是 Color.Red 但所有文本都是 green 。

【问题讨论】:

  • 您使用的是哪个 Excel 库?
  • 你是如何测试的?对象 ExcelColorType 是什么?它是自定义枚举吗?我会尝试简化您的条件以检查条件之外的所有内容。例如,我会制作一列数字,要么是 1 要么是 2。然后将条件更改为 ...Font.Color = cell.Value == 1 : Color.Green : Color.Red (或类似的东西) )。
  • 我正在使用 Microsoft.Office.Interop.Excel 库。
  • 你想要相同的cell 还是相同的column
  • 我只是运行项目来查看一些结果。是的 ExcelColorType 是一个自定义枚举,仅包含 Green 和 Red 属性。我正在使用一些文本进行测试。例如,我将 cell.value2 +=“绿色触发”添加到 if 范围。当我这样做时,两个条件都会在条件发生但颜色保持绿色时触发,我希望它在同一个单元格中

标签: c# excel


【解决方案1】:

试试下面的。

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

【讨论】:

    猜你喜欢
    • 2015-01-01
    • 2017-08-07
    • 1970-01-01
    • 1970-01-01
    • 2018-10-08
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2022-01-12
    相关资源
    最近更新 更多