0

The goal is to apply border to all data bar and conditionally set Fill.Color of individual data bar within the same series. I can do one or the other, but not both. I can style data point/bar's border with Border.Width and Border.Fill.Color, but when I conditionally color the data point/bar, the border style disappear (borrowed from SO: EPPlus ColumnStacked chart data point colors ).

If SetChartPointColors() is commented out, the chart maintain data bar borders. If I run SetCharPointColors(), the border disappear even if it is run before Border.Width and Border.Fill.Color is called.

I unzip the *.xlsx and tried comparing the two chart01.xml but kept resulting in corrupted file.

enter image description here

ExcelBarChart excelBarChart = (ExcelBarChart)ws.Drawings.AddChart("ebc", eChartType.ColumnClustered);
excelBarChart.GapWidth = 5;
ExcelRange x_range = ws.Cells["A1:A10"];
ExcelRange y_range = ws.Cells["B1:B10"];
excelBarChart.Series.Add(y_range, x_range);
// SetChartPointColors(excelBarChart, 0);
excelBarChart.Series[0].Border.Width = 1;
excelBarChart.Series[0].Border.Fill.Color = System.Drawing.Color.Black;

SetChartPointColors():

public void SetChartPointColors(ExcelChart chart, int serieNumber)
{
    var chartXml = chart.ChartXml;

    var nsa = chart.WorkSheet.Drawings.NameSpaceManager.LookupNamespace("a");
    var nsuri = chartXml.DocumentElement.NamespaceURI;

    var nsm = new XmlNamespaceManager(chartXml.NameTable);
    nsm.AddNamespace("a", nsa);
    nsm.AddNamespace("c", nsuri);

    var serieNode = chart.ChartXml.SelectSingleNode(@"c:chartSpace/c:chart/c:plotArea/c:barChart/c:ser[c:idx[@val='" + serieNumber + "']]", nsm);
    var serie = chart.Series[serieNumber];
    var points = serie.Series.Length;

    for (var i = 0; i < points; i++)
    {
        var dPt = chartXml.CreateNode(XmlNodeType.Element, "dPt", nsuri);
        var idx = chartXml.CreateNode(XmlNodeType.Element, "idx", nsuri);
        var att = chartXml.CreateAttribute("val", nsuri);
        att.Value = i.ToString();
        idx.Attributes.Append(att);
        dPt.AppendChild(idx);
        var srgbClr = chartXml.CreateNode(XmlNodeType.Element, "srgbClr", nsa);
        att = chartXml.CreateAttribute("val");

        var color = System.Drawing.Color.Green;
        // outIdx is a List<int> that contains index to be colored red
        if (outIdx.Contains(i))
        {
            color = System.Drawing.Color.Red;
        }

        att.Value = $"{color.R:X2}{color.G:X2}{color.B:X2}";
        srgbClr.Attributes.Append(att);
        var solidFill = chartXml.CreateNode(XmlNodeType.Element, "solidFill", nsa);
        solidFill.AppendChild(srgbClr);

        var spPr = chartXml.CreateNode(XmlNodeType.Element, "spPr", nsuri);
        spPr.AppendChild(solidFill);

        dPt.AppendChild(spPr);
        serieNode.AppendChild(dPt);
    }
}
KMC
  • 19,548
  • 58
  • 164
  • 253

0 Answers0