如何使用C#为Excel饼图设置数据标签位置?

时间:2019-05-23 14:56:06

标签: c# epplus

我正在创建一个Excel导出,其中包含多个饼图,这些饼图是根据数据库中的数据动态创建的,这些数据已转储到电子表格中的一系列单元格中。我需要饼图的数据标签在饼图的外侧。默认情况下,数据标签设置为最合适。

我尝试使用具有eLabelPosition属性但没有运气的OutEnd来操纵数据标签的位置。这样做会使数据标签完全消失。

下面是我用来生成饼图的方法。

    private void AddPieChart(ExcelWorksheet worksheet, int firstDataRow, int firstDataColumn, int lastDataRow, int nextColumn, int firstColumn)
    {
        ExcelPieChart pieChart = worksheet.Drawings.AddChart(worksheet.Name.ToString() + " Pie Chart", eChartType.Pie3D) as ExcelPieChart;
        var serie = pieChart.Series.Add(ExcelCellBase.GetAddress(firstDataRow + 3, firstDataColumn, lastDataRow + 3, firstDataColumn),
                                        ExcelCellBase.GetAddress(firstDataRow + 3, firstColumn, lastDataRow + 3, firstColumn));

        pieChart.DataLabel.ShowCategory = true;
        pieChart.DataLabel.ShowLeaderLines = true;
        pieChart.DataLabel.Font.Bold = true;
        pieChart.DataLabel.Font.Size = 12;
        pieChart.Legend.Remove();
        pieChart.SetSize(500, 350);
        pieChart.SetPosition(lastDataRow + 5, 0, nextColumn - 1, 0);
        pieChart.Border.Fill.Color = Color.White;
        pieChart.Series.Chart.RoundedCorners = false;

        var pieSerie = (ExcelPieChartSerie)serie;
        pieSerie.DataLabel.Position = eLabelPosition.OutEnd;
    }

1 个答案:

答案 0 :(得分:0)

如果您已将DataLabel属性分配给ExcelPieChart,然后又尝试在DataLabel上分配ExcelPieChartSerie属性,则该属性不适用于ExcelPieChartSerie。为了解决此问题,请删除DataLabel上的任何ExcelPieChart属性,然后将它们添加到ExcelPieChartSerie中,如下所示。

private void AddPieChart(ExcelWorksheet worksheet, int firstDataRow, int firstDataColumn, int lastDataRow, int nextColumn, int firstColumn)
        {
            ExcelPieChart pieChart = worksheet.Drawings.AddChart(worksheet.Name.ToString() + " Pie Chart", eChartType.Pie3D) as ExcelPieChart;
            var serie = pieChart.Series.Add(ExcelCellBase.GetAddress(firstDataRow + 3, firstDataColumn, lastDataRow + 3, firstDataColumn),
                                            ExcelCellBase.GetAddress(firstDataRow + 3, firstColumn, lastDataRow + 3, firstColumn));
            pieChart.Legend.Remove();
            pieChart.SetSize(500, 350);
            pieChart.SetPosition(lastDataRow + 5, 0, nextColumn - 1, 0);
            pieChart.Border.Fill.Color = Color.White;
            pieChart.Series.Chart.RoundedCorners = false;

            var pieSerie = (ExcelPieChartSerie)serie;
            pieSerie.DataLabel.ShowCategory = true;
            pieSerie.DataLabel.ShowLeaderLines = true;
            pieSerie.DataLabel.Font.Bold = true;
            pieSerie.DataLabel.Font.Size = 12;
            pieSerie.DataLabel.Position = eLabelPosition.OutEnd;
        }