【问题标题】:How to color a half of an excel cell?如何为excel单元格的一半着色?
【发布时间】:2016-08-31 08:01:14
【问题描述】:

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

我使用“Microsoft.Office.Interop.Excel”库。

我该怎么做?

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

【问题讨论】:

标签: c# excel ms-office office-interop


【解决方案1】:

这 (a) 可能是作弊 (b) 作为评论可能更好(但这样就不会有图像)和 (c) 可能在这里扩展 [excel] 标记的重要性,但可能对提到CF可以实现类似的东西:

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

=$B1<0  

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

=$B1>0  

作弊的部分是 B:C 的宽度被缩小并被格式化为 Center Across Selection。

有些东西非常模糊与 Sparklines 相似:

在评论中(带有图片链接)@BrakNicku 指出可以应用数据栏(并且该图片证明可以用颜色填充 Excel 单元格的一半)。一种变体,也是 Data Bars,其长度与基础值成正比:

【讨论】:

  • 你能说一下用C#怎么做吗?
  • 也可以用 CF 数据条模拟这种格式(最小值和最大值都设置为 0)sample
  • @h.o.m.a.n 你可以用EPPlus设置DataBars
【解决方案2】:

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

  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

【讨论】:

  • @pnuts 根据你的帖子(你提供了 wondefurl 图片)和 BrakNicku 的评论,我决定使用 vba 宏为 excel 单元格的一半着色并通过 C# 运行它。
猜你喜欢
  • 2011-08-19
  • 1970-01-01
  • 1970-01-01
  • 2011-08-17
  • 1970-01-01
  • 2013-09-01
  • 2014-07-31
  • 2012-10-15
相关资源
最近更新 更多