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.

ChartFromScratch.java 8.8KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187
  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.awt.geom.Rectangle2D;
  21. import java.io.BufferedReader;
  22. import java.io.FileInputStream;
  23. import java.io.FileOutputStream;
  24. import java.io.OutputStream;
  25. import java.nio.charset.StandardCharsets;
  26. import java.nio.file.Files;
  27. import java.nio.file.Paths;
  28. import java.util.ArrayList;
  29. import java.util.List;
  30. import org.apache.poi.ss.util.CellRangeAddress;
  31. import org.apache.poi.util.Units;
  32. import org.apache.poi.xddf.usermodel.chart.AxisCrossBetween;
  33. import org.apache.poi.xddf.usermodel.chart.AxisCrosses;
  34. import org.apache.poi.xddf.usermodel.chart.AxisPosition;
  35. import org.apache.poi.xddf.usermodel.chart.AxisTickMark;
  36. import org.apache.poi.xddf.usermodel.chart.BarDirection;
  37. import org.apache.poi.xddf.usermodel.chart.BarGrouping;
  38. import org.apache.poi.xddf.usermodel.chart.ChartTypes;
  39. import org.apache.poi.xddf.usermodel.chart.LegendPosition;
  40. import org.apache.poi.xddf.usermodel.chart.XDDFBarChartData;
  41. import org.apache.poi.xddf.usermodel.chart.XDDFChartAxis;
  42. import org.apache.poi.xddf.usermodel.chart.XDDFChartLegend;
  43. import org.apache.poi.xddf.usermodel.chart.XDDFDataSource;
  44. import org.apache.poi.xddf.usermodel.chart.XDDFDataSourcesFactory;
  45. import org.apache.poi.xddf.usermodel.chart.XDDFNumericalDataSource;
  46. import org.apache.poi.xddf.usermodel.chart.XDDFValueAxis;
  47. import org.apache.poi.xslf.usermodel.XMLSlideShow;
  48. import org.apache.poi.xslf.usermodel.XSLFChart;
  49. import org.apache.poi.xslf.usermodel.XSLFGraphicFrame;
  50. import org.apache.poi.xslf.usermodel.XSLFShape;
  51. import org.apache.poi.xslf.usermodel.XSLFSlide;
  52. /**
  53. * Build a chart without reading template file
  54. */
  55. @SuppressWarnings({"java:S106","java:S4823","java:S1192"})
  56. public final class ChartFromScratch {
  57. private ChartFromScratch() {}
  58. private static void usage(){
  59. System.out.println("Usage: ChartFromScratch <bar-chart-data.txt>");
  60. System.out.println(" bar-chart-data.txt the model to set. First line is chart title, " +
  61. "then go pairs {axis-label value}");
  62. }
  63. public static void main(String[] args) throws Exception {
  64. if(args.length < 1) {
  65. usage();
  66. return;
  67. }
  68. try (BufferedReader modelReader = Files.newBufferedReader(Paths.get(args[0]), StandardCharsets.UTF_8)) {
  69. String chartTitle = modelReader.readLine(); // first line is chart title
  70. String[] series = modelReader.readLine().split(",");
  71. // Category Axis Data
  72. List<String> listLanguages = new ArrayList<>(10);
  73. // Values
  74. List<Double> listCountries = new ArrayList<>(10);
  75. List<Double> listSpeakers = new ArrayList<>(10);
  76. // set model
  77. String ln;
  78. while((ln = modelReader.readLine()) != null) {
  79. String[] vals = ln.split(",");
  80. listCountries.add(Double.valueOf(vals[0]));
  81. listSpeakers.add(Double.valueOf(vals[1]));
  82. listLanguages.add(vals[2]);
  83. }
  84. String[] categories = listLanguages.toArray(new String[0]);
  85. Double[] values1 = listCountries.toArray(new Double[0]);
  86. Double[] values2 = listSpeakers.toArray(new Double[0]);
  87. try (XMLSlideShow ppt = new XMLSlideShow()) {
  88. createSlideWithChart(ppt, chartTitle, series, categories, values1, values2);
  89. createSlideWithChart(ppt, chartTitle, series, categories, values1, values2);
  90. createSlideWithChart(ppt, chartTitle, series, categories, values1, values2);
  91. // save the result
  92. try (OutputStream out = new FileOutputStream("chart-from-scratch.pptx")) {
  93. ppt.write(out);
  94. }
  95. }
  96. try (FileInputStream is = new FileInputStream("chart-from-scratch.pptx")) {
  97. try (XMLSlideShow ppt = new XMLSlideShow(is)) {
  98. for (XSLFSlide slide : ppt.getSlides()) {
  99. for (XSLFShape shape : slide.getShapes()) {
  100. if (shape instanceof XSLFGraphicFrame) {
  101. XSLFGraphicFrame frame = (XSLFGraphicFrame) shape;
  102. if (frame.hasChart()) {
  103. System.out.println(frame.getChart().getTitleShape().getText());
  104. }
  105. }
  106. }
  107. }
  108. }
  109. }
  110. }
  111. System.out.println("Done");
  112. }
  113. private static void createSlideWithChart(XMLSlideShow ppt, String chartTitle, String[] series, String[] categories,
  114. Double[] values1, Double[] values2) {
  115. XSLFSlide slide = ppt.createSlide();
  116. XSLFChart chart = ppt.createChart();
  117. Rectangle2D rect2D = new java.awt.Rectangle(fromCM(1.5), fromCM(4), fromCM(22), fromCM(14));
  118. slide.addChart(chart, rect2D);
  119. setBarData(chart, chartTitle, series, categories, values1, values2);
  120. }
  121. private static int fromCM(double cm) {
  122. return (int) (Math.rint(cm * Units.EMU_PER_CENTIMETER));
  123. }
  124. private static void setBarData(XSLFChart chart, String chartTitle, String[] series, String[] categories, Double[] values1, Double[] values2) {
  125. // Use a category axis for the bottom axis.
  126. XDDFChartAxis bottomAxis = chart.createCategoryAxis(AxisPosition.BOTTOM);
  127. bottomAxis.setTitle(series[2]);
  128. XDDFValueAxis leftAxis = chart.createValueAxis(AxisPosition.LEFT);
  129. leftAxis.setTitle(series[0]+","+series[1]);
  130. leftAxis.setCrosses(AxisCrosses.AUTO_ZERO);
  131. leftAxis.setMajorTickMark(AxisTickMark.OUT);
  132. leftAxis.setCrossBetween(AxisCrossBetween.BETWEEN);
  133. final int numOfPoints = categories.length;
  134. final String categoryDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, COLUMN_LANGUAGES, COLUMN_LANGUAGES));
  135. final String valuesDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, COLUMN_COUNTRIES, COLUMN_COUNTRIES));
  136. final String valuesDataRange2 = chart.formatRange(new CellRangeAddress(1, numOfPoints, COLUMN_SPEAKERS, COLUMN_SPEAKERS));
  137. final XDDFDataSource<?> categoriesData = XDDFDataSourcesFactory.fromArray(categories, categoryDataRange, COLUMN_LANGUAGES);
  138. final XDDFNumericalDataSource<? extends Number> valuesData = XDDFDataSourcesFactory.fromArray(values1, valuesDataRange, COLUMN_COUNTRIES);
  139. valuesData.setFormatCode("General");
  140. values1[6] = 16.0; // if you ever want to change the underlying data, it has to be done before building the data source
  141. final XDDFNumericalDataSource<? extends Number> valuesData2 = XDDFDataSourcesFactory.fromArray(values2, valuesDataRange2, COLUMN_SPEAKERS);
  142. valuesData2.setFormatCode("General");
  143. XDDFBarChartData bar = (XDDFBarChartData) chart.createData(ChartTypes.BAR, bottomAxis, leftAxis);
  144. bar.setBarGrouping(BarGrouping.CLUSTERED);
  145. XDDFBarChartData.Series series1 = (XDDFBarChartData.Series) bar.addSeries(categoriesData, valuesData);
  146. series1.setTitle(series[0], chart.setSheetTitle(series[COLUMN_COUNTRIES - 1], COLUMN_COUNTRIES));
  147. XDDFBarChartData.Series series2 = (XDDFBarChartData.Series) bar.addSeries(categoriesData, valuesData2);
  148. series2.setTitle(series[1], chart.setSheetTitle(series[COLUMN_SPEAKERS - 1], COLUMN_SPEAKERS));
  149. bar.setVaryColors(true);
  150. bar.setBarDirection(BarDirection.COL);
  151. chart.plot(bar);
  152. XDDFChartLegend legend = chart.getOrAddLegend();
  153. legend.setPosition(LegendPosition.LEFT);
  154. legend.setOverlay(false);
  155. chart.setTitleText(chartTitle);
  156. chart.setTitleOverlay(false);
  157. chart.setAutoTitleDeleted(false);
  158. }
  159. private static final int COLUMN_LANGUAGES = 0;
  160. private static final int COLUMN_COUNTRIES = 1;
  161. private static final int COLUMN_SPEAKERS = 2;
  162. }