如何为 excel 单元格的一半着色?

How to color a half of an excel cell?

背景:我需要用红色或绿色为 excele 单元格着色。如果单元格大于零,我需要将单元格着色为绿色(从单元格中间向右),如果单元格小于零,我需要将单元格着色为红色(从单元格中间向左) ).

我使用 "Microsoft.Office.Interop.Excel" 库。

我该怎么做?

P.S。 Cell color changing In Excel using C# 不是重复的,因为我只想给 excel 单元格的一半着色,而不是完整的。

这 (a) 可能是作弊 (b) 作为评论可能更好(但那样就不会有图像)和 (c) 可能在这里延伸了 [excel] 标签的重要性,但是提到 CF 可以实现某种目的可能会有些兴趣:

ColumnB(红色填充)正在使用以下公式规则进行格式化:

=$B1<0  

和 ColumnC(绿色填充)的公式规则为:

=$B1>0  

作弊的部分是 B:C 宽度减小了,并且格式化了 Center Across Selection。

有些东西非常模糊与迷你图相似:

在评论中(对图像使用 link)@BrakNicku 指出可以应用数据栏(并且图像证明可以将 Excel 单元格填满一半有颜色)。一种变体,也是数据条,其长度与基础值成比例:[​​=15=]

为了解决这个问题,我使用了给定的方案:

  1. 在 VBA 中创建宏(使用鼠标)。
  2. 将宏重写为一般形式。
  3. 在 C# 应用程序中保存宏。
  4. 通过 C# 将宏保存在 excel 文件 (xlsm) 中。
  5. 运行 来自 C# 的宏。

给定的宏:

Sub CreateGistograms(r As String)
    Range(r).Select
    Selection.FormatConditions.AddDatabar
    Selection.FormatConditions(Selection.FormatConditions.Count).ShowValue = True
    Selection.FormatConditions(Selection.FormatConditions.Count).SetFirstPriority
    With Selection.FormatConditions(1)
        .MinPoint.Modify newtype:=xlConditionValueAutomaticMin
        .MaxPoint.Modify newtype:=xlConditionValueAutomaticMax
    End With
    With Selection.FormatConditions(1).BarColor
        .Color = 8700771
            .TintAndShade = 0
        End With
        Selection.FormatConditions(1).BarFillType = xlDataBarFillGradient
        Selection.FormatConditions(1).Direction = xlContext
        Selection.FormatConditions(1).NegativeBarFormat.ColorType = xlDataBarColor
        Selection.FormatConditions(1).BarBorder.Type = xlDataBarBorderSolid
        Selection.FormatConditions(1).NegativeBarFormat.BorderColorType = _
            xlDataBarColor
        With Selection.FormatConditions(1).BarBorder.Color
            .Color = 8700771
        .TintAndShade = 0
    End With
    Selection.FormatConditions(1).AxisPosition = xlDataBarAxisAutomatic
    With Selection.FormatConditions(1).AxisColor
        .Color = 0
        .TintAndShade = 0
    End With
    With Selection.FormatConditions(1).NegativeBarFormat.Color
        .Color = 255
        .TintAndShade = 0
    End With
    With Selection.FormatConditions(1).NegativeBarFormat.BorderColor
        .Color = 255
        .TintAndShade = 0
    End With
End Sub

如何从 C# 中保存宏和 运行 他 create macro at runtime in dotnet