gpt4 book ai didi

c# - 如何以编程方式设置单元格颜色 epplus?

转载 作者:IT王子 更新时间:2023-10-29 04:24:35 24 4
gpt4 key购买 nike

我想知道是否可以使用 epplus 以编程方式设置单元格颜色?

我从一个 sql 存储过程加载我的数据并且它运​​行良好,但我的用户想要包含“年假”字样的单元格的背景颜色为浅黄色,而不是默认的白色。有没有办法做到这一点?也许通过遍历数据表?下面是哪里

public void ExportTableData(DataTable dtdata)
{
//Using EPPLUS to export Spreadsheets
ExcelPackage pck = new ExcelPackage();
var ws = pck.Workbook.Worksheets.Add("Availability list");

ws.Cells["A1"].LoadFromDataTable(dtdata, true);

ws.Cells["A1:G1"].Style.Font.Bold = true;
ws.Cells["A1:G1"].Style.Font.UnderLine = true;

//change cell color depending on the text input from stored proc?
if (dtdata.Rows[4].ToString() == "Annual Leave")
{
ws.Cells["E1"].Style.Fill.PatternType = ExcelFillStyle.Solid;
ws.Cells["E1"].Style.Fill.BackgroundColor.SetColor(Color.LightYellow);
}

pck.SaveAs(Response.OutputStream);
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment; filename=Availability.xlsx");
Response.End();
}

最佳答案

检查你的线路:

if (dtdata.Rows[4].ToString() == "Annual Leave")

如果它是一个标准的 .net 表,.ToString() 不会计算为 "System.Data.DataRow" 吗?此外,ws.Cells["E1"] 还需要在遍历行计数后针对每个单元格进行调整(基本上是 krillgar 所说的)。

类似的东西:

[TestMethod]
public void Cell_Color_Background_Test()
{
//http://stackoverflow.com/questions/28679602/how-to-set-cell-color-programmatically-epplus

//Throw in some data
var dtdata = new DataTable("tblData");
dtdata.Columns.Add(new DataColumn("Col1", typeof(string)));
dtdata.Columns.Add(new DataColumn("Col2", typeof(int)));
dtdata.Columns.Add(new DataColumn("Col3", typeof(int)));

for (var i = 0; i < 20; i++)
{
var row = dtdata.NewRow();
row["Col1"] = "Available";
row["Col2"] = i * 10;
row["Col3"] = i * 100;
dtdata.Rows.Add(row);
}
//throw in one cell that triggers
dtdata.Rows[10]["Col1"] = "Annual leave";

var existingFile = new FileInfo(@"c:\temp\temp.xlsx");
if (existingFile.Exists)
existingFile.Delete();

using (var pck = new ExcelPackage(existingFile))
{
//Using EPPLUS to export Spreadsheets
var ws = pck.Workbook.Worksheets.Add("Availability list");

ws.Cells["A1"].LoadFromDataTable(dtdata, true);

ws.Cells["A1:G1"].Style.Font.Bold = true;
ws.Cells["A1:G1"].Style.Font.UnderLine = true;

//change cell color depending on the text input from stored proc?
//if (dtdata.Rows[4].ToString() == "Annual Leave")
for (var i = 0; i < dtdata.Rows.Count; i++)
{
if (dtdata.Rows[i]["Col1"].ToString() == "Annual leave")
{
ws.Cells[i + 1, 1].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
ws.Cells[i + 1, 1].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightYellow);
}
}

pck.Save();
}

关于c# - 如何以编程方式设置单元格颜色 epplus?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28679602/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com