在EPPlus中改变线条系列的颜色

时间:2017-01-25 22:31:51

标签: c# epplus epplus-4

是否有更简单的方法来改变系列的颜色?

我尝试使用this。但是serieNode正在NullReferenceException处产生serieNode.AppendChild(spPr);

以下是生成图表的代码:

private void GenerateLicenseUsageStatsChart(FileInfo excelFileInfo, FileInfo 
                                           csvFileInfo, DateTime lastCheckedDate)
    {
        string worksheetsName = "Sheet1";
        const bool firstRowIsHeader = false;

        var excelTextFormat = new ExcelTextFormat { Delimiter = ',' };
        // excelTextFormat.EOL = "\r";

        using (ExcelPackage package = new ExcelPackage(excelFileInfo))
        {
            ExcelWorksheet worksheet = package.Workbook.Worksheets.Add(worksheetsName);

            worksheet.Cells["A1"].LoadFromText(csvFileInfo, excelTextFormat, 
                      OfficeOpenXml.Table.TableStyles.None, firstRowIsHeader);

            var workbook = package.Workbook;
            ExcelWorksheet workSheet = workbook.Worksheets[1];

            var chart = workSheet.Drawings.AddChart("chart", 
                                              eChartType.ColumnClustered);
            chart.SetPosition(10, 250);
            chart.SetSize(700, 500);
            chart.Title.Text = $"LicenseUsageStats {lastCheckedDate:MMM} 
                         {lastCheckedDate.Year}";

            chart.YAxis.MajorUnit = 1;
            chart.YAxis.MinorUnit = 1;

            chart.XAxis.MajorTickMark = eAxisTickMark.None;
            chart.XAxis.MinorTickMark = eAxisTickMark.None;
            chart.XAxis.Title.Text = "Hour";
            chart.XAxis.Title.Font.Size = 10;

            var maxLicensesSerie = chart.Series.Add("B2:B25", "A2:A25");
            maxLicensesSerie.Header = "Max Licenses Used";

            var avgLicensesSerie = chart.Series.Add("C2:C25", "A2: A25");
            avgLicensesSerie.Header = "Avg Licenses Used";

            var maxLineChart = (ExcelLineChart) 
                            chart.PlotArea.ChartTypes.Add(eChartType.Line);
            var maxThreshLineSerie = maxLineChart.Series.Add("D2:D25", 
                                                             "A2:A25");
            maxThreshLineSerie.Header = "Max";

            SetLineChartColor(maxLineChart, 0, Color.Red);

            var warningLineChart = 
             (ExcelLineChart)chart.PlotArea.ChartTypes.Add(eChartType.Line);
            var warningThreshLineSerie = 
                 warningLineChart.Series.Add("E2:E25", "A2:A25");
            warningThreshLineSerie.Header = "Warning";

            SetLineChartColor(warningLineChart, 1, Color.Yellow);

            worksheet.Cells[worksheet.Dimension.Address].AutoFitColumns();

            // workSheet.Column(4).Hidden = true;
            // workSheet.Column(5).Hidden = true;

            package.Save();
        }
    }

我的最终目标: My end goal

由于excel没有创建水平线条的简洁方法,因此我创建了max和warning列。我也想隐藏这些列,而不会影响图形。也许我可以"隐藏"把它们移到另一张纸上呢?

1 个答案:

答案 0 :(得分:2)

我看到了问题。该函数假定serie的索引与图表对象集合中的系列数匹配。但是,因为它是一个混合图表,在投射Add的结果后并非如此。这有点像黑客但它会起作用(我真的应该想一下如何匹配数字):

public static void SetLineChartColor(this ExcelChart chart, int serieIdx, int chartSeriesIndex, Color color)
{
    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:lineChart/c:ser[c:idx[@val='{serieIdx}']]", nsm);
    var serie = chart.Series[chartSeriesIndex];
    var points = serie.Series.Length;

    //Add reference to the color for the legend
    var srgbClr = chartXml.CreateNode(XmlNodeType.Element, "srgbClr", nsa);
    var att = chartXml.CreateAttribute("val");
    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 ln = chartXml.CreateNode(XmlNodeType.Element, "ln", nsa);
    ln.AppendChild(solidFill);

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

    serieNode.AppendChild(spPr);
}

你可以这样称呼它:

maxLineChart.SetLineChartColor(2, 0, Color.Red);
warningLineChart.SetLineChartColor(3, 0, Color.Yellow);