c# - 关闭的 XML 根据单元格值更改整行背景颜色

标签 c# excel closedxml

我正在尝试根据单元格选择(值)为整行着色。我想仅为工作表中使用的范围更改行的颜色,而不是未使用的单元格。

这是我现在拥有的代码:

class Program
{
    static void Main(string[] args)
    {
        CreateWorkbook();
    }

    static void CreateWorkbook()
    {
        var workbook = new XLWorkbook();
        var ws1 = workbook.AddWorksheet("Main");
        var ws2 = workbook.AddWorksheet("ListOfOptions");

        var listOfStrings = new List<String>();
        listOfStrings.Add(" ");
        listOfStrings.Add("Edit");
        listOfStrings.Add("Delete");

        ws2.Cell(2,2).InsertData(listOfStrings);
        workbook.Worksheet(1).Column(3).SetDataValidation().List(ws2.Range("B2:B4"), true);

        var list = new List<Person>();
        list.Add(new Person() { Name = "John", Age = 30, Action = " " });
        list.Add(new Person() { Name = "Mary", Age = 15, Action = " " });
        list.Add(new Person() { Name = "Luis", Age = 21, Action = " " });
        list.Add(new Person() { Name = "Henry", Age = 45, Action = " " });

        ws1.Cell(1, 1).InsertData(list.AsEnumerable());

        ws1.RangeUsed().AddConditionalFormat().WhenContains("Edit")
            .Fill.SetBackgroundColor(XLColor.Yellow);
        ws1.RangeUsed().AddConditionalFormat().WhenContains("Delete")
            .Fill.SetBackgroundColor(XLColor.Red);

        ws2.Hide(); 
        workbook.SaveAs("DemoWorkbook.xlsx");
    }

    class Person
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Action { get; set; }
    }
}

结果是这样的:
See excel screenshot

最佳答案

使用 VB.NET -

            Dim nonEmptyDataRows = ws.RowsUsed
            For Each dataRow In nonEmptyDataRows
                Dim cell As String = dataRow.Cell(29).Value
                If cell = "0" Then
                    dataRow.Style.Fill.BackgroundColor = XLColor.Yellow
                ElseIf cell = "1" Then
                    dataRow.Style.Fill.BackgroundColor = XLColor.Green
                End If
            Next

关于c# - 关闭的 XML 根据单元格值更改整行背景颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49451964/

相关文章:

c# - 如何创建类似 illustrator/photoshop 的 pentool 以在 Unity 中创建贝塞尔曲线

c# - CurrentThread/ProcessThread 对象

excel - Microsoft Excel LOOKUP 函数只是...不起作用?

c# - 使用 VLOOKUP 公式的 ClosedXML 读取行

c# - 如何将 ClosedXML 中的合并单元格范围内的图像居中

c# - 打印 Excel 工作表/工作簿

c# - 在c#中使用openxml sdk创建xlsx文件

c# - 使用 LINQ 检查计划重叠

c# - Excel 互操作 COM 不关闭

sql-server - SSIS 数据错误地进入 excel 目的地