wordpress hit counter
Welcome to OpenXML Developer Sign in | Join | Help

Changing chart type in a SpreadsheetML document

Article By - Sheela E.N, Sonata Software Limited

 

This article explains the process of changing type of chart in a SpreadsheetML document programmatically using Open XML SDK API.

 

In this article, we will be replacing a bar chart embedded in the excel work sheet to pie chart. We will be loading the pre-existing pie chart XML file instead of generating the same programmatically.

 

1.      Create a C# project; add a reference to openxml dll

 

·         In the Add Reference dialog box, click the .NET tab.

·         Scroll to the Microsoft.Office.DocumentFormat.OpenXml option, select it, and then click OK.

 

2.      Import the namespace to refer to the dll

 

using Microsoft.Office.DocumentFormat.OpenXml.Packaging;

 

3.      Declare necessary namespaces

 

string strChrtNS = "http://schemas.openxmlformats.org/officeDocument/2006/relationships/chart";

 

4.      Open the Excel document.

 

SpreadsheetDocument xlDoc = SpreadsheetDocument.Open("../../BarChart.xlsx", true);

 

5.      Get the handler for each worksheet of a workbook

 

foreach (WorksheetPart wrkSh in xlDoc.WorkbookPart.WorksheetParts)

 

6.      For a given worksheet, search for chart object

 

foreach (IdPartPair var2 in part.Parts)

 

if (var2.OpenXmlPart.RelationshipType.ToString() == strChrtNS)

 

7.      If chart object is found, load the xml file having pie chart into the openxml part and save

 

ChartPart chartType = (ChartPart)var2.OpenXmlPart;

XmlDocument xmlDoc = new XmlDocument();

xmlDoc.Load("../../Piechart1.xml");

xmlDoc.Save(chartType.GetStream(FileMode.Create, FileAccess.Write));

 

8.      Close the excel handler

 

xlDoc.Close();

 

 

This is a simple demo which demonstrates ease of use of Open XML SDK for replacing types of charts in Excel 2007 document. The example demo is attached with the article as a zip file.
Published Friday, September 28, 2007 8:00 AM by SanjayKumarM
Filed Under: , ,
Attachment(s): ExcelChartTypeSDKDemo.zip

Comments

 

KittyKit said:

hi Sheela

The downloaded code works well. But when I tried to implement it in my aspx project, I face the problem that the Relationshiptype is "http://schemas.openxmlformats.org/officeDocument/2006/relationships/drawing" and the innermost loop is not executed. When I changed the strChrtNS string(removed chart and added drawing as the last part) I had to change the
ChartPart chartType = (ChartPart)var2.OpenXmlPart;
to
DrawingsPart chartType = (DrawingsPart)var2.OpenXmlPart;
And still it didnt work :(( the chart disappeared after I run the application. any help would be appreciated.
thanks
Kirthi
May 18, 2010 4:17 PM
Anonymous comments are disabled