Creating and Adding a Chart to a Spreadsheet

From Apache OpenOffice Wiki
Jump to: navigation, search

Charts are used in spreadsheet documents to visualize the data that they contain. A spreadsheet is one single sheet in a spreadsheet document and offers a interface, that is required by the service With this interface, a collection of table charts that are a container for the actual charts can be accessed. To retrieve the chart document model from a table chart object, use the method getEmbeddedObject().

The following example shows how to insert a chart into a spreadsheet document and retrieve its chart document model. The example assumes that there is a to insert the chart and an array of cell range addresses that contain the regions in which the data for the chart can be found. Refer to Spreadsheet Documents for more information about how to get or create these objects. The following snippet shows how to insert a chart into a Calc document.

  final String sChartName = "MyChart"; aSheet;[] aAddresses;
  // get the sheet in which you want to insert a chart
  // and query it for XTableChartsSupplier and store it in aSheet
  // also get an array of CellRangeAddresses containing
  // the data you want to visualize and store them in aAddresses
  // for details see documentation of Spreadsheets
  // ...
  XChartDocument aChartDocument = null; aChartCollection = aSheet.getCharts();
  XNameAccess aChartCollectionNA = (XNameAccess) UnoRuntime.queryInterface(
      XNameAccess.class, aChartCollection );
  // only insert the chart if it does not already exist
  if (aChartCollectionNA != null && !aChartCollectionNA.hasByName(sChartName)) {
      // following rectangle parameters are measured in 1/100 mm aRect = new, 1000, 15000, 9271);
      // first bool: ColumnHeaders
      // second bool: RowHeaders
      aChartCollection.addNewByName(sChartName, aRect, aAddresses, true, false);
      try {
 aTableChart = (
          // the table chart is an embedded object which contains the chart document
          aChartDocument = (XChartDocument) UnoRuntime.queryInterface(
              ((XEmbeddedObjectSupplier) UnoRuntime.queryInterface(
                  aTableChart )).getEmbeddedObject());
      } catch ( ex) {
          System.out.println("Couldn't find chart with name " + sChartName + ": " + ex); 
  // now aChartDocument should contain an XChartDocument representing the newly inserted chart
Content on this page is licensed under the Public Documentation License (PDL).
Personal tools
In other languages