C#教程

关注公众号 jb51net

关闭
首页 > 软件编程 > C#教程 > C# Excel隔行设置颜色

C#代码实现使用条件格式为Excel隔行设置颜色

作者:2501_93070778

对于数据较多的工作表,为相邻行设置不同的背景颜色,可以帮助区分数据行,本文将介绍如何在 C# 和 VB.NET 中使用条件格式为 Excel 工作表设置交替行颜色,并结合相关的 .NET Excel 处理组件完成操作,感兴趣的小伙伴可以了解下

对于数据较多的工作表,为相邻行设置不同的背景颜色,可以帮助区分数据行,让内容更容易查看和阅读。实现隔行变色的方法有很多,例如使用 Excel 内置的表格样式,或者通过条件格式设置规则。本文将介绍如何在 C# 和 VB.NET 中使用条件格式为 Excel 工作表设置交替行颜色,并结合相关的 .NET Excel 处理组件完成操作。

安装相关 .NET 组件

开始之前,需要在 .NET 项目中添加用于处理 Excel 文件的相关 DLL 文件。你可以从组件的官方资源中获取安装包,也可以通过 NuGet 安装相应的程序包。

PM> Install-Package Spire.XLS

使用条件格式为 Excel 隔行设置颜色

以下是使用条件格式为 Excel 工作表中的奇偶行设置不同颜色的基本步骤:

完整示例代码如下:

using Spire.Xls;
using Spire.Xls.Core;
using Spire.Xls.Core.Spreadsheet.Collections;
using System.Drawing;

namespace AlternateRowColors
{
    class Program
    {
        static void Main(string[] args)
        {
            // 创建一个 Workbook 对象
            Workbook workbook = new Workbook();

            // 加载 Excel 文件
            workbook.LoadFromFile(@"C:\Users\Administrator\Desktop\sample.xlsx");
            
            // 获取第一个工作表
            Worksheet sheet = workbook.Worksheets[0];

            // 为工作表添加条件格式
            XlsConditionalFormats format = sheet.ConditionalFormats.Add();

            // 设置应用条件格式的单元格区域
            format.AddRange(sheet.Range[2, 1, sheet.LastRow, sheet.LastColumn]);

            // 添加条件,根据公式更改单元格格式
            IConditionalFormat condition1 = format.AddCondition();        
            condition1.FirstFormula = "=MOD(ROW(),2)=0";
            condition1.FormatType = ConditionalFormatType.Formula;
            condition1.BackColor = Color.Yellow;

            // 添加另一个条件,根据公式更改单元格格式
            IConditionalFormat condition2 = format.AddCondition();
            condition2.FirstFormula = "=MOD(ROW(),2)=1";
            condition2.FormatType = ConditionalFormatType.Formula;
            condition2.BackColor = Color.LightSeaGreen;

            // 将工作簿保存为 Excel 文件
            workbook.SaveToFile("AlternateRowColors.xlsx", ExcelVersion.Version2016);
        }
    }
}

知识扩展

在 C# 中为 Excel 隔行设置颜色,使用条件格式比手动填充更优雅——数据增删后,颜色会自动调整,无需重新设置。核心是添加一条基于公式的规则,公式为:=MOD(ROW(),2)=0

这条公式会对偶数行应用格式;若要奇数行,改为 =MOD(ROW(),2)=1。

下面整理几种主流库的实现方案。

方案一:EPPlus(开源免费,推荐)

EPPlus 从 5.0 开始支持条件格式,API 直观。非商业用途免费。

安装:Install-Package EPPlus

using OfficeOpenXml;
using OfficeOpenXml.Style;
using System.Drawing;

public static void SetAlternatingRowColorsWithEPPlus(string filePath)
{
    // 非商业用途许可证
    ExcelPackage.LicenseContext = LicenseContext.NonCommercial;

    using (var package = new ExcelPackage())
    {
        var ws = package.Workbook.Worksheets.Add("数据");

        // 1. 准备示例数据
        ws.Cells["A1"].Value = "姓名";
        ws.Cells["B1"].Value = "年龄";
        ws.Cells["C1"].Value = "城市";
        ws.Cells["A2"].Value = "张三";
        ws.Cells["B2"].Value = 25;
        ws.Cells["C2"].Value = "北京";
        ws.Cells["A3"].Value = "李四";
        ws.Cells["B3"].Value = 30;
        ws.Cells["C3"].Value = "上海";
        ws.Cells["A4"].Value = "王五";
        ws.Cells["B4"].Value = 28;
        ws.Cells["C4"].Value = "广州";
        ws.Cells["A5"].Value = "赵六";
        ws.Cells["B5"].Value = 35;
        ws.Cells["C5"].Value = "深圳";

        // 2. 定义要应用条件格式的区域(数据行从第2行开始)
        var dataRange = ws.Cells["A2:C100"];

        // 3. 添加基于公式的条件格式
        var cf = ws.ConditionalFormatting.AddExpression(dataRange);
        cf.Formula = "MOD(ROW(),2)=0";   // 偶数行上色
        cf.Style.Fill.PatternType = ExcelFillStyle.Solid;
        cf.Style.Fill.BackgroundColor.Color = Color.LightGray;

        // 可选:添加第二条规则给奇数行(如需两种颜色交替)
        // var cf2 = ws.ConditionalFormatting.AddExpression(dataRange);
        // cf2.Formula = "MOD(ROW(),2)=1";
        // cf2.Style.Fill.PatternType = ExcelFillStyle.Solid;
        // cf2.Style.Fill.BackgroundColor.Color = Color.WhiteSmoke;

        package.SaveAs(new FileInfo(filePath));
    }
}

调用:

SetAlternatingRowColorsWithEPPlus(@"C:\temp\隔行变色_EPPlus.xlsx");

方案二:Aspose.Cells(商业库,功能全面)

Aspose.Cells 通过 FormatCondition 添加表达式规则,适合企业级项目。

安装:Install-Package Aspose.Cells

using Aspose.Cells;
using System.Drawing;

public static void SetAlternatingRowColorsWithAspose(string filePath)
{
    Workbook workbook = new Workbook();
    Worksheet sheet = workbook.Worksheets[0];

    // 1. 准备示例数据
    sheet.Cells["A1"].PutValue("姓名");
    sheet.Cells["B1"].PutValue("年龄");
    sheet.Cells["C1"].PutValue("城市");
    sheet.Cells["A2"].PutValue("张三");
    sheet.Cells["B2"].PutValue(25);
    sheet.Cells["C2"].PutValue("北京");
    sheet.Cells["A3"].PutValue("李四");
    sheet.Cells["B3"].PutValue(30);
    sheet.Cells["C3"].PutValue("上海");
    sheet.Cells["A4"].PutValue("王五");
    sheet.Cells["B4"].PutValue(28);
    sheet.Cells["C4"].PutValue("广州");

    // 2. 添加条件格式集合
    int index = sheet.ConditionalFormattings.Add();
    FormatConditionCollection fcc = sheet.ConditionalFormattings[index];

    // 3. 设置应用区域 A2:C100
    CellArea area = CellArea.CreateCellArea("A2", "C100");
    fcc.AddArea(area);

    // 4. 添加表达式条件
    int condIndex = fcc.AddCondition(FormatConditionType.Expression);
    FormatCondition condition = fcc[condIndex];
    condition.Formula1 = "=MOD(ROW(),2)=0";   // 偶数行
    condition.Style.BackgroundColor = Color.LightGray;
    condition.Style.Pattern = BackgroundType.Solid;

    workbook.Save(filePath);
}

方案三:ClosedXML(开源免费,MIT 协议)

ClosedXML 的 API 非常简洁,适合喜欢链式调用的开发者。

安装:Install-Package ClosedXML

using ClosedXML.Excel;

public static void SetAlternatingRowColorsWithClosedXML(string filePath)
{
    using (var workbook = new XLWorkbook())
    {
        var ws = workbook.Worksheets.Add("数据");

        // 1. 准备示例数据
        ws.Cell("A1").Value = "姓名";
        ws.Cell("B1").Value = "年龄";
        ws.Cell("C1").Value = "城市";
        ws.Cell("A2").Value = "张三";
        ws.Cell("B2").Value = 25;
        ws.Cell("C2").Value = "北京";
        ws.Cell("A3").Value = "李四";
        ws.Cell("B3").Value = 30;
        ws.Cell("C3").Value = "上海";
        ws.Cell("A4").Value = "王五";
        ws.Cell("B4").Value = 28;
        ws.Cell("C4").Value = "广州";

        // 2. 对区域添加条件格式
        var range = ws.Range("A2:C100");
        var cf = range.AddConditionalFormat();

        // 3. 使用公式条件:偶数行填充浅灰色
        cf.When(Formula).Is("MOD(ROW(),2)=0")
          .Fill.SetBackgroundColor(XLColor.LightGray);

        workbook.SaveAs(filePath);
    }
}

注意:ClosedXML 中 Formula 是 XLConditionalFormatType 的枚举值,需要 using ClosedXML.Excel;。

方案四:Spire.XLS(商业库,有免费版)

Spire.XLS 的 ConditionalFormatType.Formula 可以直接设置公式和背景色。

安装:Install-Package Spire.XLS

using Spire.Xls;
using System.Drawing;

public static void SetAlternatingRowColorsWithSpire(string filePath)
{
    Workbook workbook = new Workbook();
    Worksheet sheet = workbook.Worksheets[0];

    // 1. 准备数据
    sheet.Range["A1"].Value = "姓名";
    sheet.Range["B1"].Value = "年龄";
    sheet.Range["C1"].Value = "城市";
    sheet.Range["A2"].Value = "张三";
    sheet.Range["B2"].Value = 25;
    sheet.Range["C2"].Value = "北京";
    sheet.Range["A3"].Value = "李四";
    sheet.Range["B3"].Value = 30;
    sheet.Range["C3"].Value = "上海";

    // 2. 添加条件格式
    var formats = sheet.ConditionalFormats;
    var format = formats.Add();

    // 3. 设置应用区域和公式
    format.Range = sheet.Range["A2:C100"];
    format.FormatType = ConditionalFormatType.Formula;
    format.FirstFormula = "MOD(ROW(),2)=0";
    format.BackColor = Color.LightGray;

    workbook.SaveToFile(filePath, ExcelVersion.Version2016);
}

方案五:Open XML SDK(免费,底层控制)

Open XML SDK 是微软官方库,但条件格式的 XML 结构较复杂,需要手动构建多个元素。

安装:Install-Package DocumentFormat.OpenXml

using DocumentFormat.OpenXml;
using DocumentFormat.OpenXml.Packaging;
using DocumentFormat.OpenXml.Spreadsheet;
public static void SetAlternatingRowColorsWithOpenXml(string filePath)
{
    using (SpreadsheetDocument doc = SpreadsheetDocument.Create(filePath, SpreadsheetDocumentType.Workbook))
    {
        // 创建工作簿部件
        WorkbookPart workbookPart = doc.AddWorkbookPart();
        workbookPart.Workbook = new Workbook();
        // 创建工作表
        WorksheetPart worksheetPart = workbookPart.AddNewPart<WorksheetPart>();
        worksheetPart.Worksheet = new Worksheet(new SheetData());
        Sheets sheets = doc.WorkbookPart.Workbook.AppendChild(new Sheets());
        Sheet sheet = new Sheet()
        {
            Id = doc.WorkbookPart.GetIdOfPart(worksheetPart),
            SheetId = 1,
            Name = "数据"
        };
        sheets.Append(sheet);
        // 构建条件格式(简化示意,完整实现需定义 dxf 样式)
        ConditionalFormatting conditionalFormatting = new ConditionalFormatting()
        {
            SequenceOfReferences = new ListValue<StringValue>() { InnerText = "A2:C100" }
        };
        Formula formula = new Formula("MOD(ROW(),2)=0");
        ConditionalFormattingRule rule = new ConditionalFormattingRule()
        {
            Type = ConditionalFormatValues.Expression,
            Priority = 1,
            FormatId = 0  // 需在 DifferentialFormats 中定义对应样式
        };
        rule.Append(formula);
        conditionalFormatting.Append(rule);
        worksheetPart.Worksheet.Append(conditionalFormatting);
        workbookPart.Workbook.Save();
    }
}

说明:Open XML SDK 实现条件格式需要额外创建 DifferentialFormats 部件并定义 dxf 样式,代码量较大。除非有特殊底层控制需求,否则建议使用前四种方案。

总结

通过条件格式,可以根据行号自动为 Excel 工作表中的奇数行和偶数行设置不同的背景颜色,从而让数据更加清晰、易于查看。本文通过 C# 示例,首先加载 Excel 文件并获取目标工作表,然后设置需要应用条件格式的区域,并利用 MOD 和 ROW 函数判断当前行是奇数行还是偶数行,分别应用不同的颜色。最后,将设置完成的工作簿保存为新的 Excel 文件。

这种方法无需逐行修改单元格格式,当工作表中的数据发生变化时,条件格式也可以根据规则自动调整,适用于数据量较大的 Excel 表格。

到此这篇关于C#代码实现使用条件格式为Excel隔行设置颜色的文章就介绍到这了,更多相关C# Excel隔行设置颜色内容请搜索脚本之家以前的文章或继续浏览下面的相关文章希望大家以后多多支持脚本之家!

您可能感兴趣的文章:
阅读全文