You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

BarChartDemo.java 7.6KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170
  1. /*
  2. * ====================================================================
  3. * Licensed to the Apache Software Foundation (ASF) under one or more
  4. * contributor license agreements. See the NOTICE file distributed with
  5. * this work for additional information regarding copyright ownership.
  6. * The ASF licenses this file to You under the Apache License, Version 2.0
  7. * (the "License"); you may not use this file except in compliance with
  8. * the License. You may obtain a copy of the License at
  9. *
  10. * http://www.apache.org/licenses/LICENSE-2.0
  11. *
  12. * Unless required by applicable law or agreed to in writing, software
  13. * distributed under the License is distributed on an "AS IS" BASIS,
  14. * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  15. * See the License for the specific language governing permissions and
  16. * limitations under the License.
  17. * ====================================================================
  18. */
  19. package org.apache.poi.examples.xslf;
  20. import java.io.BufferedReader;
  21. import java.io.FileInputStream;
  22. import java.io.FileOutputStream;
  23. import java.io.OutputStream;
  24. import java.nio.charset.StandardCharsets;
  25. import java.nio.file.Files;
  26. import java.nio.file.Paths;
  27. import java.util.ArrayList;
  28. import java.util.List;
  29. import org.apache.poi.ooxml.POIXMLDocumentPart;
  30. import org.apache.poi.ss.util.CellRangeAddress;
  31. import org.apache.poi.xddf.usermodel.chart.AxisOrientation;
  32. import org.apache.poi.xddf.usermodel.chart.AxisPosition;
  33. import org.apache.poi.xddf.usermodel.chart.BarDirection;
  34. import org.apache.poi.xddf.usermodel.chart.XDDFBarChartData;
  35. import org.apache.poi.xddf.usermodel.chart.XDDFChartData;
  36. import org.apache.poi.xddf.usermodel.chart.XDDFDataSource;
  37. import org.apache.poi.xddf.usermodel.chart.XDDFDataSourcesFactory;
  38. import org.apache.poi.xddf.usermodel.chart.XDDFNumericalDataSource;
  39. import org.apache.poi.xslf.usermodel.XMLSlideShow;
  40. import org.apache.poi.xslf.usermodel.XSLFChart;
  41. import org.apache.poi.xslf.usermodel.XSLFSlide;
  42. /**
  43. * Build a bar chart from a template pptx
  44. */
  45. @SuppressWarnings({"java:S106","java:S4823","java:S1192"})
  46. public final class BarChartDemo {
  47. private BarChartDemo() {}
  48. private static void usage(){
  49. System.out.println("Usage: BarChartDemo <bar-chart-template.pptx> <bar-chart-data.txt>");
  50. System.out.println(" bar-chart-template.pptx template with a bar chart");
  51. System.out.println(" bar-chart-data.txt the model to set. First line is chart title, " +
  52. "then go pairs {axis-label value}");
  53. }
  54. public static void main(String[] args) throws Exception {
  55. if(args.length < 2) {
  56. usage();
  57. return;
  58. }
  59. try (FileInputStream argIS = new FileInputStream(args[0]);
  60. BufferedReader modelReader = Files.newBufferedReader(Paths.get(args[1]), StandardCharsets.UTF_8)) {
  61. String chartTitle = modelReader.readLine(); // first line is chart title
  62. String seriesText = modelReader.readLine();
  63. String[] series = seriesText == null ? new String[0] : seriesText.split(",");
  64. // Category Axis Data
  65. List<String> listLanguages = new ArrayList<>(10);
  66. // Values
  67. List<Double> listCountries = new ArrayList<>(10);
  68. List<Double> listSpeakers = new ArrayList<>(10);
  69. // set model
  70. String ln;
  71. while((ln = modelReader.readLine()) != null) {
  72. String[] vals = ln.split(",");
  73. listCountries.add(Double.valueOf(vals[0]));
  74. listSpeakers.add(Double.valueOf(vals[1]));
  75. listLanguages.add(vals[2]);
  76. }
  77. String[] categories = listLanguages.toArray(new String[0]);
  78. Double[] values1 = listCountries.toArray(new Double[0]);
  79. Double[] values2 = listSpeakers.toArray(new Double[0]);
  80. try (XMLSlideShow pptx = new XMLSlideShow(argIS)) {
  81. XSLFSlide slide = pptx.getSlides().get(0);
  82. setBarData(findChart(slide), chartTitle, series, categories, values1, values2);
  83. XSLFChart chart = findChart(pptx.createSlide().importContent(slide));
  84. setColumnData(chart, "Column variant");
  85. // save the result
  86. try (OutputStream out = new FileOutputStream("bar-chart-demo-output.pptx")) {
  87. pptx.write(out);
  88. }
  89. }
  90. }
  91. }
  92. private static void setBarData(XSLFChart chart, String chartTitle, String[] series, String[] categories, Double[] values1, Double[] values2) {
  93. final List<XDDFChartData> data = chart.getChartSeries();
  94. final XDDFBarChartData bar = (XDDFBarChartData) data.get(0);
  95. final int numOfPoints = categories.length;
  96. final String categoryDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, COLUMN_LANGUAGES, COLUMN_LANGUAGES));
  97. final String valuesDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, COLUMN_COUNTRIES, COLUMN_COUNTRIES));
  98. final String valuesDataRange2 = chart.formatRange(new CellRangeAddress(1, numOfPoints, COLUMN_SPEAKERS, COLUMN_SPEAKERS));
  99. final XDDFDataSource<?> categoriesData = XDDFDataSourcesFactory.fromArray(categories, categoryDataRange, COLUMN_LANGUAGES);
  100. final XDDFNumericalDataSource<? extends Number> valuesData = XDDFDataSourcesFactory.fromArray(values1, valuesDataRange, COLUMN_COUNTRIES);
  101. values1[6] = 16.0; // if you ever want to change the underlying data, it has to be done before building the data source
  102. final XDDFNumericalDataSource<? extends Number> valuesData2 = XDDFDataSourcesFactory.fromArray(values2, valuesDataRange2, COLUMN_SPEAKERS);
  103. XDDFChartData.Series series1 = bar.getSeries(0);
  104. series1.replaceData(categoriesData, valuesData);
  105. series1.setTitle(series[0], chart.setSheetTitle(series[0], COLUMN_COUNTRIES));
  106. XDDFChartData.Series series2 = bar.addSeries(categoriesData, valuesData2);
  107. series2.setTitle(series[1], chart.setSheetTitle(series[1], COLUMN_SPEAKERS));
  108. chart.plot(bar);
  109. chart.setTitleText(chartTitle);
  110. // chart.setTitleOverlay(overlay);
  111. // adjust font size for readability
  112. bar.getCategoryAxis().getOrAddTextProperties().setFontSize(11.5);
  113. chart.getTitle().getOrAddTextProperties().setFontSize(18.2);
  114. }
  115. private static void setColumnData(XSLFChart chart, String chartTitle) {
  116. // Series Text
  117. List<XDDFChartData> series = chart.getChartSeries();
  118. XDDFBarChartData bar = (XDDFBarChartData) series.get(0);
  119. // in order to transform a bar chart into a column chart, you just need to change the bar direction
  120. bar.setBarDirection(BarDirection.COL);
  121. // looking for "Stacked Bar Chart"? uncomment the following line
  122. // bar.setBarGrouping(BarGrouping.STACKED);
  123. // additionally, you can adjust the axes
  124. bar.getCategoryAxis().setOrientation(AxisOrientation.MAX_MIN);
  125. bar.getValueAxes().get(0).setPosition(AxisPosition.TOP);
  126. }
  127. private static XSLFChart findChart(XSLFSlide slide) {
  128. // find chart in the slide
  129. XSLFChart chart = null;
  130. for(POIXMLDocumentPart part : slide.getRelations()){
  131. if(part instanceof XSLFChart){
  132. chart = (XSLFChart) part;
  133. break;
  134. }
  135. }
  136. if(chart == null) {
  137. throw new IllegalStateException("chart not found in the template");
  138. }
  139. return chart;
  140. }
  141. private static final int COLUMN_LANGUAGES = 0;
  142. private static final int COLUMN_COUNTRIES = 1;
  143. private static final int COLUMN_SPEAKERS = 2;
  144. }