web-dev-qa-db-fra.com

Comment définir la couleur des cellules par programme epplus?

Je me demandais s'il était possible de définir la couleur des cellules par programme en utilisant epplus?

Je charge mes données à partir d'une procédure stockée SQL et cela fonctionne bien, mais mes utilisateurs souhaitent que les cellules contenant les mots "Congé annuel" aient une couleur d'arrière-plan jaune clair au lieu du blanc par défaut. Y a-t-il un moyen de faire cela? peut-être en parcourant un datatable peut-être? Voici où

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();
}
24
wubblyjuggly

Vérifiez votre ligne:

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

S'il s'agit d'une table .net standard, .ToString() n'évaluerait-il pas "System.Data.DataRow"? ws.Cells["E1"] Devra également être ajusté pour chaque cellule après avoir parcouru le nombre de lignes (essentiellement ce que disait krillgar).

Quelque chose comme ca:

[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();
    }
26
Ernie

Merci Ernie! Je l'ai légèrement modifié pour permettre mon en-tête dans Excel et pour également m'assurer que le code ne démarre pas à E1. J'ai utilisé ws.cells [i + 2, 5] pour ce faire. À votre santé!

   for (var i = 0; i < dtdata.Rows.Count; i++)
        {

            if (dtdata.Rows[i]["typeName"].ToString() == "Annual Leave")
            {
                ws.Cells[i + 2, 5].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                ws.Cells[i + 2, 5].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightYellow);
            }

            else if (dtdata.Rows[i]["typeName"].ToString() == "Available")
            {
                ws.Cells[i + 2, 5].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                ws.Cells[i + 2, 5].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.LightGreen);
            }
            else
            {
                ws.Cells[i + 2, 5].Style.Fill.PatternType = OfficeOpenXml.Style.ExcelFillStyle.Solid;
                ws.Cells[i + 2, 5].Style.Fill.BackgroundColor.SetColor(System.Drawing.Color.White);
            }
        }
4
wubblyjuggly

Vous pouvez essayer d'utiliser l'option de mise en forme conditionnelle dans EPPlus

voici leur exemple

et voici un SO post avec quelqu'un d'autre qui a utilisé cette option

Généralement, l'utilisation de liens comme réponses n'est pas mon style, mais aucune raison de refaire ces roues, si l'échantillon EPP disparaît, je suppose, et si l'échantillon SO est parti, je suppose donc avec cette répondre.

J'espère que ça aide

0
workabyte