使用 openxml 创建折线图

本文关键字:折线图 创建 openxml 使用 | 更新日期: 2023-09-27 17:56:52

我正在尝试在 excel 工作表上创建一个新的折线图,我不知道我如何在此图表上感受数据以及如何为每个系列添加值。以下是我尝试做的事情:

    static void Main(string[] args)
    {
        string docName = @"myFile.xlsx";
        string worksheetName = "Sheet1";
        string title = "My Chart";
        InsertChartInSpreadsheet(docName, worksheetName, title);
    }

    private static void InsertChartInSpreadsheet(string docName, string worksheetName, string title)
    {
    // Open Document for editing
        using (SpreadsheetDocument document = SpreadsheetDocument.Open(docName, true))
        {
            IEnumerable<Sheet> sheets = document.WorkbookPart.Workbook.Descendants<Sheet>().
    Where(s => s.Name == worksheetName);
            if (sheets.Count() == 0)
            {
                // The specified worksheet does not exist.
                return;
            }
            WorksheetPart worksheetPart = (WorksheetPart)document.WorkbookPart.GetPartById(sheets.First().Id);
            // Add a new drawing to the worksheet.
            DrawingsPart drawingsPart = worksheetPart.AddNewPart<DrawingsPart>();
            worksheetPart.Worksheet.Append(new DocumentFormat.OpenXml.Spreadsheet.Drawing() { Id = worksheetPart.GetIdOfPart(drawingsPart) });
            worksheetPart.Worksheet.Save();
            // Add a new chart and set the chart language to English-US.
            ChartPart chartPart = drawingsPart.AddNewPart<ChartPart>();
            chartPart.ChartSpace = new ChartSpace();
            chartPart.ChartSpace.Append(new EditingLanguage() { Val = new StringValue("en-US") });
            DocumentFormat.OpenXml.Drawing.Charts.Chart chart = chartPart.ChartSpace.AppendChild<DocumentFormat.OpenXml.Drawing.Charts.Chart>(
                new DocumentFormat.OpenXml.Drawing.Charts.Chart());
            // Create a new clustered column chart.
            PlotArea plotArea = chart.AppendChild<PlotArea>(new PlotArea());
            Layout layout = plotArea.AppendChild<Layout>(new Layout());
            uint i = 0;
            LineChart lineChart = plotArea.AppendChild<LineChart>(new LineChart());
            LineChartSeries[] series = new LineChartSeries() {} ;
            uint j ; 
            // add series to the lineChart
            for (LineChartSeries s in series) {
                s = lineChart.AppendChild<LineChartSeries>(new LineChartSeries());
                s.SeriesText = new SeriesText(new NumericValue() { Text = "Ser "+j } );
                series1.Index = new Index() { Val = new UInt32Value(j) };
                series1.Order = new Order() { Val = new UInt32Value(j) } ;
                j++;
            }
            i = 1;
            /***
            Here is my question , how can i add values to my chart
            Example data: 
                    Ser1    Ser2    Ser3    Ser4
            2010    5       6       12      41
            2011    65      1       31      43
            2012    75      8       64      40
            2013    12      31      47      66
            ***/
            // Save the chart part.
            chartPart.ChartSpace.Save();
            /* Here i'll add the position of the chart on the worksheet */ 
            // Save the WorksheetDrawing object.
            drawingsPart.WorksheetDrawing.Save();
        }
    }

上面的代码中,我给出了一个我想在图表上感受到的数据示例:

                    Ser1    Ser2    Ser3    Ser4
            2010    5       6       12      41
            2011    65      1       31      43
            2012    75      8       64      40
            2013    12      31      47      66

我是C#和OpenXml的初学者,请帮助我:-)谢谢。

使用 openxml 创建折线图

经过几个小时的搜索,终于我通过使用电子表格灯库找到了这个问题的解决方案,这个库与我想要的不一样,但最后我得到了我希望的结果。SpreadSheetLight,帮助我轻松地从DataTable创建图表,然后我使用以下函数将图表从excel文件复制到新的PowerPoint文件:

    public CopyChartFromXlsx2Pptx(string SourceFile, string TargetFile, string targetppt)
    {
        ChartPart chartPart;
        ChartPart newChartPart;
        //SlidePart slidepartbkMark = null;
        string chartPartIdBookMark = null;
        File.Copy(TargetFile, targetppt, true);
        //Powerpoint document
        using (OpenXmlPkg.PresentationDocument pptPackage = OpenXmlPkg.PresentationDocument.Open(targetppt, true))
        {
            OpenXmlPkg.PresentationPart presentationPart = pptPackage.PresentationPart;
            var secondSlidePart = pptPackage.PresentationPart.SlideParts.Skip(0).First();  // this will retrieve your second slide
            chartPart = secondSlidePart.ChartParts.First();
            chartPartIdBookMark = secondSlidePart.GetIdOfPart(chartPart);
            //Console.WriteLine("ID:"+chartPartIdBookMark.ToString());
            secondSlidePart.DeletePart(chartPart);
            secondSlidePart.Slide.Save();
            newChartPart = secondSlidePart.AddNewPart<ChartPart>(chartPartIdBookMark);
            ChartPart saveXlsChart = null;
            using (SpreadsheetDocument xlsDocument = SpreadsheetDocument.Open(SourceFile.ToString(), true))
            {
                WorkbookPart xlsbookpart = xlsDocument.WorkbookPart;
                foreach (var worksheetPart in xlsDocument.WorkbookPart.WorksheetParts)
                {
                    if (worksheetPart.DrawingsPart != null)
                        if (worksheetPart.DrawingsPart.ChartParts.Any())
                        {
                            saveXlsChart = worksheetPart.DrawingsPart.ChartParts.First();
                        }
                }
                newChartPart.FeedData(saveXlsChart.GetStream());
                //newChartPart.FeedData(
                secondSlidePart.Slide.Save();
                xlsDocument.Close();
                pptPackage.Close();
            }
        }
    }

在我可以删除生成的 excel 文件后:-)

希望这个解决方案能帮到你!