使用 OpenXml 更改 Excel 工作表中的特定单元格背景颜色 [英] Changing specific cell background color in excel sheet using OpenXml

查看:312
本文介绍了使用 OpenXml 更改 Excel 工作表中的特定单元格背景颜色的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要求更改 Excel 工作表中一行单元格的背景颜色.

My requirement to change background color of cells in a row of a excel sheet.

例如:如果 A1 单元格值小于 100,我需要将其显示在红色背景中.

ex : if A1 cell value is less than 100, i need to show it in Red Background.

我搜索了很多,我找到了一些代码来创建样式表

I searched alot, i found some code to create stylesheets from this

http://blogs.msdn.com/b/chrisquon/archive/2009/11/30/stylizing-your-excel-worksheets-with-open-xml-2-0.aspx

该代码正在使用 StyleIndex 属性.而且非常复杂.有没有其他解决办法……??????

that code is using StyleIndex property. And its very complex. Is there any other solution...???????

推荐答案

为了操作 OpenXML 格式的电子表格,原始 SDK 有几个包装器可以让事情变得更简单,例如

For manipulating spreadsheets in OpenXML format there are several wrappers around the raw SDK that make things much simpler, e.g.

使用 ClosedXML,您可以使用条件格式来实现您想要的结果(参见 文档):

Using ClosedXML you could use conditional formatting to achieve your desired result (see documentation):

using (var wb = new XLWorkbook())
{
    using (var ws = wb.AddWorksheet("Test"))
    {
        ws.Cell("A1").Value = 42;
        ws.Cell("A1").AddConditionalFormat().WhenLessThan(100)
            .Fill.SetBackgroundColor(XLColor.Red);
    }
    wb.SaveAs(@"C:\Dev\Test.xlsx");
}

这篇关于使用 OpenXml 更改 Excel 工作表中的特定单元格背景颜色的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆