Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

EPPlus how to change colors of PIE Chart in EXCEL

Tags:

c#

epplus

How to change the default colors of Excel Pie Chart using EPPlus programatically.

below is my code

var pieChart = worksheet.Drawings.AddChart("piechart", eChartType.Pie3D) as ExcelPieChart;
            //Set top left corner to row 1 column 2
            pieChart.SetPosition(18, 0, 0, 0);
            pieChart.SetSize(350, 300);
            pieChart.Series.Add(ExcelRange.GetAddress(12, 2, 15, 2),ExcelRange.GetAddress(12, 1, 15, 1) );
            pieChart.Legend.Position = eLegendPosition.Bottom;
            pieChart.Legend.Border.Fill.Color = Color.Green;
            pieChart.Legend.Border.LineStyle = eLineStyle.Solid;              
            pieChart.Legend.Border.Fill.Style = eFillStyle.SolidFill;
            pieChart.Title.Text = "Current Status";               
            pieChart.DataLabel.ShowCategory = false;
            pieChart.DataLabel.ShowPercent = true;

I want to change the default colors to the some bright colors.

Suggest and throw some light on this.

like image 427
PRAVEEN SARAF Avatar asked Sep 02 '14 12:09

PRAVEEN SARAF


People also ask

How do I change the color of my pie chart in Excel based on value?

Select the bar chart or column chart, then click Kutools > Charts > Color Chart by Value. Then in the popped-out dialog, set the value range and the relative color as you need. Click to free download now!


2 Answers

Inspired by Ernie's answer, here is an extension method that works for setting the color and thickness of a line chart series, and a non tested version for setting the color of a pie chart data point:

public static void SetSeriesStyle(this ExcelLineChart chart, ExcelChartSerie series, Color color, decimal? thickness = null) {
    if (thickness < 0) throw new ArgumentOutOfRangeException("thickness");
    var i = 0;
    var found = false;
    foreach (var s in chart.Series) {
        if (s == series) {
            found = true;
            break;
        }
        ++i;
    }
    if (!found) throw new InvalidOperationException("series not found.");
    //Get the nodes
    var nsm = chart.WorkSheet.Drawings.NameSpaceManager;
    var nschart = nsm.LookupNamespace("c");
    var nsa = nsm.LookupNamespace("a");
    var node = chart.ChartXml.SelectSingleNode(@"c:chartSpace/c:chart/c:plotArea/c:lineChart/c:ser[c:idx[@val='" + i.ToString(CultureInfo.InvariantCulture) + "']]", nsm);
    var doc = chart.ChartXml;

    //Add the solid fill node
    var spPr = doc.CreateElement("c:spPr", nschart);
    var ln = spPr.AppendChild(doc.CreateElement("a:ln", nsa));
    if (thickness.HasValue) {
        var w = ln.Attributes.Append(doc.CreateAttribute("w"));
        w.Value = Math.Round(thickness.Value * 12700).ToString(CultureInfo.InvariantCulture);
        var cap = ln.Attributes.Append(doc.CreateAttribute("cap"));
        cap.Value = "rnd";
    }
    var solidFill = ln.AppendChild(doc.CreateElement("a:solidFill", nsa));
    var srgbClr = solidFill.AppendChild(doc.CreateElement("a:srgbClr", nsa));
    var valattrib = srgbClr.Attributes.Append(doc.CreateAttribute("val"));

    //Set the color
    valattrib.Value = color.ToHex().Substring(1);
    node.AppendChild(spPr);
}

public static void SetDataPointStyle(this ExcelPieChart chart, int dataPointIndex, Color color) {
    //Get the nodes
    var nsm = chart.WorkSheet.Drawings.NameSpaceManager;
    var nschart = nsm.LookupNamespace("c");
    var nsa = nsm.LookupNamespace("a");
    var node = chart.ChartXml.SelectSingleNode("c:chartSpace/c:chart/c:plotArea/c:pieChart/c:ser", nsm);
    var doc = chart.ChartXml;
    //Add the node
    //Create the data point node
    var dPt = doc.CreateElement("c:dPt", nschart);

    var idx = dPt.AppendChild(doc.CreateElement("c:idx", nschart));
    var valattrib = idx.Attributes.Append(doc.CreateAttribute("val"));
    valattrib.Value = dataPointIndex.ToString(CultureInfo.InvariantCulture);
    node.AppendChild(dPt);

    //Add the solid fill node
    var spPr = doc.CreateElement("c:spPr", nschart);
    var solidFill = spPr.AppendChild(doc.CreateElement("a:solidFill", nsa));
    var srgbClr = solidFill.AppendChild(doc.CreateElement("a:srgbClr", nsa));
    valattrib = srgbClr.Attributes.Append(doc.CreateAttribute("val"));

    //Set the color
    valattrib.Value = color.ToHex().Substring(1);
    dPt.AppendChild(spPr);
}

public static String ToHex(this Color c) {
    return "#" + c.R.ToString("X2") + c.G.ToString("X2") + c.B.ToString("X2");
}

Usage:

lineChart.SetSeriesStyle(s, color: Color.FromArgb(0, 0, 0), thickness: 6m);
pieChart.SetDataPointStyle(dataPointIndex: 0, color: Color.FromArgb(0, 0, 0));
like image 68
Erwin Mayer Avatar answered Oct 13 '22 08:10

Erwin Mayer


Just thought I would give back a little as I ran into a similar problem. Short answer is EEPlus does not support the ability to change the colors of the individual slices so I had to rely on xml manipulation. Not pretty and requires good knowledge of the data you are outputting - you need to know the number of slices you are expecting. But it works and this should be applicable to other pie chart types besides 3D.

Here is a test method that demonstrates. Did this against EPP 4.0.1 but should work just as well with prior versions:

[TestMethod]
public void Change_3DPieChart_Color()
{
    const string PIE_PATH = "c:chartSpace/c:chart/c:plotArea/c:pie3DChart/c:ser";

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

    using (var package = new ExcelPackage(existingFile))
    {
        var workbook = package.Workbook;
        var worksheet = workbook.Worksheets.Add("newsheet");

        //Some data
        worksheet.Cells["A12"].Value = "wer";
        worksheet.Cells["A13"].Value = "sdf";
        worksheet.Cells["A14"].Value = "wer";
        worksheet.Cells["A15"].Value = "ghgh";

        worksheet.Cells["B12"].Value = 53;
        worksheet.Cells["B13"].Value = 36;
        worksheet.Cells["B14"].Value = 43;
        worksheet.Cells["B15"].Value = 86;

        //Create the pie
        var pieChart = (ExcelPieChart) worksheet.Drawings.AddChart("piechart", eChartType.Pie3D);

        //Set top left corner to row 1 column 2
        pieChart.SetPosition(18, 0, 0, 0);
        pieChart.SetSize(350, 300);
        pieChart.Series.Add(ExcelCellBase.GetAddress(12, 2, 15, 2), ExcelCellBase.GetAddress(12, 1, 15, 1));
        pieChart.Legend.Position = eLegendPosition.Bottom;
        pieChart.Legend.Border.Fill.Color = Color.Green;
        pieChart.Legend.Border.LineStyle = eLineStyle.Solid;
        pieChart.Legend.Border.Fill.Style = eFillStyle.SolidFill;
        pieChart.Title.Text = "Current Status";
        pieChart.DataLabel.ShowCategory = false;
        pieChart.DataLabel.ShowPercent = true;

        //Get the nodes
        var ws = pieChart.WorkSheet;
        var nsm = ws.Drawings.NameSpaceManager;
        var nschart = nsm.LookupNamespace("c");
        var nsa = nsm.LookupNamespace("a");
        var node = pieChart.ChartXml.SelectSingleNode(PIE_PATH, nsm);
        var doc = pieChart.ChartXml;

        //Add the node
        var rand = new Random();
        for (var i = 0; i < 4; i++)
        {
            //Create the data point node
            var dPt = doc.CreateElement("dPt", nschart);

            var idx = dPt.AppendChild(doc.CreateElement("idx", nschart));
            var valattrib = idx.Attributes.Append(doc.CreateAttribute("val"));
            valattrib.Value = i.ToString(CultureInfo.InvariantCulture);
            node.AppendChild(dPt);

            //Add the solid fill node
            var spPr = doc.CreateElement("spPr", nschart);
            var solidFill = spPr.AppendChild(doc.CreateElement("solidFill", nsa));
            var srgbClr = solidFill.AppendChild(doc.CreateElement("srgbClr", nsa));
            valattrib = srgbClr.Attributes.Append(doc.CreateAttribute("val"));

            //Set the color
            var color = Color.FromArgb(rand.Next(256), rand.Next(256), rand.Next(256));
            valattrib.Value = ColorTranslator.ToHtml(color).Replace("#", String.Empty);
            dPt.AppendChild(spPr);
        }

        package.Save();

    }
}
like image 35
Ernie S Avatar answered Oct 13 '22 07:10

Ernie S