0

I'm new to OpenXML,here i'm trying to export chart data to powerpoint.Here in the code i trying to save it as excel file and then to powerpoint,while trying click on the export button it showing me an error message(Written as aheading).here i'm my code.

    protected void btnExport_Click(object sender, EventArgs e)
    {

        try
        {
            // Open an existing Presentation

            PresentationDocument oPDoc = PresentationDocument.Open(@"D:\Chart.pptx", true);

            PresentationPart oPPart = oPDoc.PresentationPart;

            // Get the ReleationshipId of the first Slide

            SlideId slideId = oPPart.Presentation.SlideIdList.GetFirstChild<SlideId>();

            string relId = slideId.RelationshipId;

            // Get the slide part by the relationship ID.

            SlidePart slidePart = (SlidePart)oPPart.GetPartById(relId);

            // Add a new chart part

            ChartPart chPrt = slidePart.AddNewPart<ChartPart>();

            XmlDocument xDoc = new XmlDocument();

            String strFileName = "D:\\chart1.xml";

            xDoc.Load(strFileName);

            StreamWriter objDocMainWrt = new StreamWriter(chPrt.GetStream(FileMode.Create, FileAccess.Write));

            xDoc.Save(objDocMainWrt);

            // Add the data Sheet for the Chart

            ExtendedPart objEmbPart = chPrt.AddExtendedPart("http://schemas.openxmlformats.org/officeDocument/2006/relationships/package", "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", ".xlsx");

            strFileName = "D:\\chartData.xlsx";

            FileStream partStream = new FileStream(strFileName, FileMode.Open, FileAccess.Read);

            objEmbPart.FeedData(partStream);

            // Change the Data releation ID used in Chart.xml

            // Elemenet changed : c:externalData

            string relChtDataID = chPrt.GetIdOfPart(objEmbPart);

            XmlNamespaceManager nsManager1 = new XmlNamespaceManager(xDoc.NameTable);

            XmlNamespaceManager nsManagerDraw = new XmlNamespaceManager(xDoc.NameTable);

            //nsManager1.AddNamespace("c", "http://schemas.openxmlformats.org/drawingml/2006/chart");

            nsManagerDraw.AddNamespace("d", "http://schemas.openxmlformats.org/drawingml/2006/chart");

            //XmlNodeList nodeTest = xDoc.SelectNodes("//c:externalData", nsManager1);
            XmlNodeList nodeTest = xDoc.SelectNodes("//d:chart1", nsManagerDraw);

            foreach (XmlNode node in nodeTest)
            {

                node.Attributes["r:id"].Value = relChtDataID;

            }

            // Save changes back to Chart.xml

            xDoc.Save(chPrt.GetStream(FileMode.Create, FileAccess.Write));

            // Get the SlidePart Stream

            const string presentationmlNamespace = "http://schemas.openxmlformats.org/presentationml/2006/main";

            NameTable nt = new NameTable();

            XmlNamespaceManager nsManager = new XmlNamespaceManager(nt);

            nsManager.AddNamespace("p", presentationmlNamespace);

            XmlDocument presXML = new XmlDocument(nt);

            presXML.Load(slidePart.GetStream());



            // Get the spTree Element in SlidePart

            XmlNode nodeTree = presXML.SelectSingleNode("//p:spTree", nsManager);

            string rid = slidePart.GetIdOfPart(chPrt).ToString();

            // Generate the Graphic Element for the Chart

            XmlNode childNode = GenerateNode(rid);

            //Append the Graphic Element to spTree Element in SlidePart

            nodeTree.AppendChild(presXML.ImportNode(childNode, true));

            Stream o = slidePart.GetStream();

            presXML.Save(o);

            oPDoc.Close();
        }
        catch (Exception msg)
        {
            Response.Write(msg.ToString());
        }
    }
private XmlNode GenerateNode(String rId)
    {

        XmlDocument xwb = new XmlDocument();

        xwb.AppendChild(xwb.CreateXmlDeclaration("1.0", "UTF-8", "yes"));

        XmlNamespaceManager xmlns = new XmlNamespaceManager(xwb.NameTable);

        xmlns.AddNamespace("p", "http://schemas.openxmlformats.org/presentationml/2006/main");

        xmlns.AddNamespace("r", "http://schemas.openxmlformats.org/officeDocument/2006/relationships");

        xmlns.AddNamespace("a", "http://schemas.openxmlformats.org/drawingml/2006/main");

        XmlElement eleGraphic = xwb.CreateElement("p:graphicFrame", xmlns.LookupNamespace("p"));

        xwb.AppendChild(eleGraphic);

        XmlElement eleGrpFrm = xwb.CreateElement("p:nvGraphicFramePr", xmlns.LookupNamespace("p"));

        eleGraphic.AppendChild(eleGrpFrm);

        XmlElement elePpr = xwb.CreateElement("p:cNvPr", xmlns.LookupNamespace("p"));

        eleGrpFrm.AppendChild(elePpr);

        XmlAttribute attrRid = xwb.CreateAttribute("id");

        attrRid.Value = "4";

        elePpr.SetAttributeNode(attrRid);

        XmlAttribute attrName = xwb.CreateAttribute("name");

        attrName.Value = "Chart 2";

        elePpr.SetAttributeNode(attrName);

        XmlElement elecNvGraphicFramePr = xwb.CreateElement("p:cNvGraphicFramePr", xmlns.LookupNamespace("p"));

        eleGrpFrm.AppendChild(elecNvGraphicFramePr);

        XmlElement elenvPr = xwb.CreateElement("p:nvPr", xmlns.LookupNamespace("p"));

        eleGrpFrm.AppendChild(elenvPr);

        XmlElement elexfrm = xwb.CreateElement("p:xfrm", xmlns.LookupNamespace("p"));

        eleGraphic.AppendChild(elexfrm);

        XmlElement eleoff = xwb.CreateElement("a:off", xmlns.LookupNamespace("a"));

        elexfrm.AppendChild(eleoff);

        XmlAttribute xvalue = xwb.CreateAttribute("x");

        xvalue.Value = "1524000";

        eleoff.SetAttributeNode(xvalue);

        XmlAttribute yvalue = xwb.CreateAttribute("y");

        yvalue.Value = "1397000";

        eleoff.SetAttributeNode(yvalue);

        XmlElement eleext = xwb.CreateElement("a:ext", xmlns.LookupNamespace("a"));

        elexfrm.AppendChild(eleext);

        XmlAttribute cxvalue = xwb.CreateAttribute("cx");

        cxvalue.Value = "6096000";

        eleext.SetAttributeNode(cxvalue);

        XmlAttribute cyvalue = xwb.CreateAttribute("cy");

        cyvalue.Value = "4064000";

        eleext.SetAttributeNode(cyvalue);

        //<c:chart xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart" xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships" r:id="rId2"/></a:graphicData></a:graphic></p:graphicFrame>

        XmlElement elegraphic = xwb.CreateElement("a:graphic", xmlns.LookupNamespace("a"));

        eleGraphic.AppendChild(elegraphic);

        XmlElement elegraphicData = xwb.CreateElement("a:graphicData", xmlns.LookupNamespace("a"));

        elegraphic.AppendChild(elegraphicData);

        XmlAttribute uri = xwb.CreateAttribute("uri");

        uri.Value = "http://schemas.openxmlformats.org/drawingml/2006/chart";

        elegraphicData.SetAttributeNode(uri);

        XmlElement elechart = xwb.CreateElement("c:chart", "http://schemas.openxmlformats.org/drawingml/2006/chart");

        elegraphicData.AppendChild(elechart);

        XmlAttribute id = xwb.CreateAttribute("r:id", xmlns.LookupNamespace("r"));

        id.Value = rId;

        elechart.SetAttributeNode(id);



        XmlNode ss1 = xwb.SelectSingleNode("//p:graphicFrame", xmlns);

        return ss1;

        //xwb.Save(@"C:\temp\test1.xml");
    }

Please let me know where i have done mistake.

shankar.parshimoni
  • 1,289
  • 5
  • 22
  • 42

1 Answers1

0

Try this below code,before that create empty ppt template and excel with two chart controls.

           string paramPresentationPath = @"D:\Chart.pptx";
            string paramWorkbookPath = @"D:\chartData.xlsx";
            object paramMissing = Type.Missing;

            powerpointApplication = new pptNS.Application();

            // Create an instance Excel.          
            excelApplication = new xlNS.Application();

            // Open the Excel workbook containing the worksheet with the chart
            // data.
            excelWorkBook = excelApplication.Workbooks.Open(paramWorkbookPath,
                            paramMissing, paramMissing, paramMissing,
                            paramMissing, paramMissing, paramMissing,
                            paramMissing, paramMissing, paramMissing,
                            paramMissing, paramMissing, paramMissing,
                            paramMissing, paramMissing);

            // Get the worksheet that contains the chart.
            targetSheet = (xlNS.Worksheet)(excelWorkBook.Worksheets[1]);//here 1 is sheet no.

            // Get the ChartObjects collection for the sheet.
            chartObjects = (xlNS.ChartObjects)(targetSheet.ChartObjects(paramMissing));

            // Get the chart to copy.
            existingChartObject = (xlNS.ChartObject)(chartObjects.Item("Chart Name in Excel"));

            // Create a PowerPoint presentation.
            pptPresentation = powerpointApplication.Presentations.Add(
                                Microsoft.Office.Core.MsoTriState.msoTrue);

            // Add a blank slide to the presentation.
            pptSlide = pptPresentation.Slides.Add(1, pptNS.PpSlideLayout.ppLayoutBlank);

            // Copy the chart from the Excel worksheet to the clipboard.
            existingChartObject.Copy();

            // Paste the chart into the PowerPoint presentation.
            shapeRange = pptSlide.Shapes.Paste();

            // Position the chart on the slide.
            shapeRange.Left = 30;
            shapeRange.Top = 100;

            // Width and Height on the Slide.
            shapeRange.Width = 600;
            shapeRange.Height = 400;


            ///<summary>
            ///Second Slide
            ///</summary>

            // Get the worksheet that contains the chart.
            targetSheet = (xlNS.Worksheet)(excelWorkBook.Worksheets[2]);

            // Get the ChartObjects collection for the sheet.
            chartObjects = (xlNS.ChartObjects)(targetSheet.ChartObjects(paramMissing));

            // Get the chart to copy.
            existingChartObject = (xlNS.ChartObject)(chartObjects.Item("Chart Name in excel"));

            //// Create a PowerPoint presentation.
            //pptPresentation = powerpointApplication.Presentations.Add(
            //                    Microsoft.Office.Core.MsoTriState.msoTrue);

            // Add a blank slide to the presentation.
            pptSlide = pptPresentation.Slides.Add(2, pptNS.PpSlideLayout.ppLayoutBlank);

            // Copy the chart from the Excel worksheet to the clipboard.
            existingChartObject.Copy();

            // Paste the chart into the PowerPoint presentation.
            shapeRange = pptSlide.Shapes.Paste();

            // Position the chart on the slide.
            shapeRange.Left = 30;
            shapeRange.Top = 100;

            // Width and Height on the Slide.
            shapeRange.Width = 600;
            shapeRange.Height = 400;


            // Save the presentation.
            pptPresentation.SaveAs(paramPresentationPath,
                            pptNS.PpSaveAsFileType.ppSaveAsOpenXMLPresentation,
                            Microsoft.Office.Core.MsoTriState.msoTrue);

            //pptPresentation.Close();

        }
        catch (Exception msg)
        {
            Response.Write(msg.ToString());
        }
        finally
        {
            shapeRange = null;
            pptSlide = null;

            object paramMissing = Type.Missing;

            // Close and release the Presentation object.
            if (pptPresentation != null)
            {
                pptPresentation.Close();
                Marshal.FinalReleaseComObject(pptPresentation);
                //Marshal.ReleaseComObject(pptPresentation.Slides);
                pptPresentation = null;
            }

            // Quit PowerPoint and release the ApplicationClass object.
            if (powerpointApplication != null)
            {
                powerpointApplication.Quit();
                Marshal.FinalReleaseComObject(powerpointApplication);
                powerpointApplication = null;
            }

            // Release the Excel objects.
            targetSheet = null;
            chartObjects = null;
            existingChartObject = null;

            //Close and release the Excel Workbook object.
            if (excelWorkBook != null)
            {
                excelWorkBook.Close(false, paramMissing, paramMissing);
                Marshal.FinalReleaseComObject(excelWorkBook);
                excelWorkBook = null;
            }

            // Quit Excel and release the ApplicationClass object.
            if (excelApplication != null)
            {
                excelApplication.Quit();
                Marshal.FinalReleaseComObject(excelApplication);
                excelApplication = null;

                //System.Runtime.InteropServices.Marshal.ReleaseComObject(excelApplication);
            }

            ////releaseObject(ref excelApplication);

            ////releaseObject(ref powerpointApplication);

            System.Diagnostics.Process[] excelprc = System.Diagnostics.Process.GetProcessesByName("EXCEL");
            if (excelprc.Length == 1)
            {
                excelprc[0].Kill();
            }

            System.Diagnostics.Process[] ppprc = System.Diagnostics.Process.GetProcessesByName("POWERPNT");
            if (ppprc.Length == 1)
            {
                ppprc[0].Kill();
            }

            GC.Collect();
            GC.WaitForPendingFinalizers();
            GC.Collect();
            GC.WaitForPendingFinalizers();
Dinesh Haraveer
  • 1,784
  • 3
  • 31
  • 54