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

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169
  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[] series = modelReader.readLine().split(",");
  63. // Category Axis Data
  64. List<String> listLanguages = new ArrayList<>(10);
  65. // Values
  66. List<Double> listCountries = new ArrayList<>(10);
  67. List<Double> listSpeakers = new ArrayList<>(10);
  68. // set model
  69. String ln;
  70. while((ln = modelReader.readLine()) != null) {
  71. String[] vals = ln.split(",");
  72. listCountries.add(Double.valueOf(vals[0]));
  73. listSpeakers.add(Double.valueOf(vals[1]));
  74. listLanguages.add(vals[2]);
  75. }
  76. String[] categories = listLanguages.toArray(new String[0]);
  77. Double[] values1 = listCountries.toArray(new Double[0]);
  78. Double[] values2 = listSpeakers.toArray(new Double[0]);
  79. try (XMLSlideShow pptx = new XMLSlideShow(argIS)) {
  80. XSLFSlide slide = pptx.getSlides().get(0);
  81. setBarData(findChart(slide), chartTitle, series, categories, values1, values2);
  82. XSLFChart chart = findChart(pptx.createSlide().importContent(slide));
  83. setColumnData(chart, "Column variant");
  84. // save the result
  85. try (OutputStream out = new FileOutputStream("bar-chart-demo-output.pptx")) {
  86. pptx.write(out);
  87. }
  88. }
  89. }
  90. }
  91. private static void setBarData(XSLFChart chart, String chartTitle, String[] series, String[] categories, Double[] values1, Double[] values2) {
  92. final List<XDDFChartData> data = chart.getChartSeries();
  93. final XDDFBarChartData bar = (XDDFBarChartData) data.get(0);
  94. final int numOfPoints = categories.length;
  95. final String categoryDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, COLUMN_LANGUAGES, COLUMN_LANGUAGES));
  96. final String valuesDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, COLUMN_COUNTRIES, COLUMN_COUNTRIES));
  97. final String valuesDataRange2 = chart.formatRange(new CellRangeAddress(1, numOfPoints, COLUMN_SPEAKERS, COLUMN_SPEAKERS));
  98. final XDDFDataSource<?> categoriesData = XDDFDataSourcesFactory.fromArray(categories, categoryDataRange, COLUMN_LANGUAGES);
  99. final XDDFNumericalDataSource<? extends Number> valuesData = XDDFDataSourcesFactory.fromArray(values1, valuesDataRange, COLUMN_COUNTRIES);
  100. values1[6] = 16.0; // if you ever want to change the underlying data, it has to be done before building the data source
  101. final XDDFNumericalDataSource<? extends Number> valuesData2 = XDDFDataSourcesFactory.fromArray(values2, valuesDataRange2, COLUMN_SPEAKERS);
  102. XDDFChartData.Series series1 = bar.getSeries(0);
  103. series1.replaceData(categoriesData, valuesData);
  104. series1.setTitle(series[0], chart.setSheetTitle(series[0], COLUMN_COUNTRIES));
  105. XDDFChartData.Series series2 = bar.addSeries(categoriesData, valuesData2);
  106. series2.setTitle(series[1], chart.setSheetTitle(series[1], COLUMN_SPEAKERS));
  107. chart.plot(bar);
  108. chart.setTitleText(chartTitle); // https://stackoverflow.com/questions/30532612
  109. // chart.setTitleOverlay(overlay);
  110. // adjust font size for readability
  111. bar.getCategoryAxis().getOrAddTextProperties().setFontSize(11.5);
  112. chart.getTitle().getOrAddTextProperties().setFontSize(18.2);
  113. }
  114. private static void setColumnData(XSLFChart chart, String chartTitle) {
  115. // Series Text
  116. List<XDDFChartData> series = chart.getChartSeries();
  117. XDDFBarChartData bar = (XDDFBarChartData) series.get(0);
  118. // in order to transform a bar chart into a column chart, you just need to change the bar direction
  119. bar.setBarDirection(BarDirection.COL);
  120. // looking for "Stacked Bar Chart"? uncomment the following line
  121. // bar.setBarGrouping(BarGrouping.STACKED);
  122. // additionally, you can adjust the axes
  123. bar.getCategoryAxis().setOrientation(AxisOrientation.MAX_MIN);
  124. bar.getValueAxes().get(0).setPosition(AxisPosition.TOP);
  125. }
  126. private static XSLFChart findChart(XSLFSlide slide) {
  127. // find chart in the slide
  128. XSLFChart chart = null;
  129. for(POIXMLDocumentPart part : slide.getRelations()){
  130. if(part instanceof XSLFChart){
  131. chart = (XSLFChart) part;
  132. break;
  133. }
  134. }
  135. if(chart == null) {
  136. throw new IllegalStateException("chart not found in the template");
  137. }
  138. return chart;
  139. }
  140. private static final int COLUMN_LANGUAGES = 0;
  141. private static final int COLUMN_COUNTRIES = 1;
  142. private static final int COLUMN_SPEAKERS = 2;
  143. }