c# Aspose.Words插入饼图PieChart

        private static void Main(string[] args)
        {
            Document doc = new Document();
            DocumentBuilder builder = new DocumentBuilder(doc);
            builder.Writeln("普通饼图:");
            AddPieChart(builder);
            builder.Writeln();
            builder.Writeln("3D饼图:");
            AddPie3dChart(builder);
            doc.Save("abc.docx");
        }

        /// <summary>
        /// 添加饼图
        /// </summary>
        private static void AddPieChart(DocumentBuilder builder)
        {
            AddPieChart(builder,ChartType.Pie,"普通饼图");
        }
        /// <summary>
        /// 添加3D饼图
        /// </summary>
        private static void AddPie3dChart(DocumentBuilder builder)
        {
            AddPieChart(builder,ChartType.Pie3D,"3D饼图");
        }

        private static void AddPieChart(DocumentBuilder builder, ChartType chatType, string title)
        {
            var shape = builder.InsertChart(chatType, 200, 200);
            Chart chart = shape.Chart;

            ChartSeriesCollection seriesCollection = chart.Series;
            seriesCollection.Clear();//清除默认
            //类别
            var categories = new string[]
            {
                "1", "2", "3", "4"
            };
            //
            var values = new double[]
            {
                20, 20, 30, 40
            };
            
            chart.Legend.Position= LegendPosition.Right;//显示在右边
            //添加数据
            var chatSeries = seriesCollection.Add(title,categories , values);
            //设置数据显示
            SetChartSeriesDataLabel(chatSeries,categories.Count());
        }

        private static void SetChartSeriesDataLabel(ChartSeries chatSeries,int count)
        {
             ChartDataLabelCollection dataLabelCollection = chatSeries.DataLabels;
            for (int i = 0; i < count; i++)
            {
                ChartDataLabel chartDataLabel = dataLabelCollection.Add(i);
                chartDataLabel.ShowLegendKey = true;
                chartDataLabel.ShowLeaderLines = true;
                chartDataLabel.ShowCategoryName = true;
                chartDataLabel.ShowPercentage = true;
                chartDataLabel.ShowSeriesName = false;
                chartDataLabel.ShowValue = true;
                chartDataLabel.Separator = "  ";
            }
        }
说明:目前还有一个问题,就是通过aspose.words插入的图表目前还不支持右键编辑数据功能,这个查看了官方的回复,说现阶段还不支持,具体的可以参考一下地址说明
https://forum.aspose.com/t/unable-to-edit-chart-data-manually-in-word-chart-using-apose-word-for-net-15-6-0/44166
https://forum.aspose.com/t/how-to-enable-data-editing-of-chart-in-ms-word/24575

 

posted @ 2018-01-25 17:48  一!雨  阅读(2822)  评论(0编辑  收藏  举报