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.

BarChartExample.java 6.5KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146
  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.xwpf.usermodel;
  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.ss.util.CellRangeAddress;
  30. import org.apache.poi.xddf.usermodel.chart.AxisOrientation;
  31. import org.apache.poi.xddf.usermodel.chart.AxisPosition;
  32. import org.apache.poi.xddf.usermodel.chart.BarDirection;
  33. import org.apache.poi.xddf.usermodel.chart.XDDFBarChartData;
  34. import org.apache.poi.xddf.usermodel.chart.XDDFChartData;
  35. import org.apache.poi.xddf.usermodel.chart.XDDFDataSource;
  36. import org.apache.poi.xddf.usermodel.chart.XDDFDataSourcesFactory;
  37. import org.apache.poi.xddf.usermodel.chart.XDDFNumericalDataSource;
  38. import org.apache.poi.xwpf.usermodel.XWPFChart;
  39. import org.apache.poi.xwpf.usermodel.XWPFDocument;
  40. /**
  41. * Build a bar chart from a template docx
  42. */
  43. @SuppressWarnings({"java:S106","java:S4823","java:S1192"})
  44. public final class BarChartExample {
  45. private BarChartExample() {}
  46. private static void usage(){
  47. System.out.println("Usage: BarChartExample <bar-chart-template.docx> <bar-chart-data.txt>");
  48. System.out.println(" bar-chart-template.docx template with a bar chart");
  49. System.out.println(" bar-chart-data.txt the model to set. First line is chart title, " +
  50. "then go pairs {axis-label value}");
  51. }
  52. public static void main(String[] args) throws Exception {
  53. if(args.length < 2) {
  54. usage();
  55. return;
  56. }
  57. try (FileInputStream argIS = new FileInputStream(args[0]);
  58. BufferedReader modelReader = Files.newBufferedReader(Paths.get(args[1]), StandardCharsets.UTF_8)) {
  59. String chartTitle = modelReader.readLine(); // first line is chart title
  60. String seriesText = modelReader.readLine();
  61. String[] series = seriesText == null ? new String[0] : seriesText.split(",");
  62. // Category Axis Data
  63. List<String> listLanguages = new ArrayList<>(10);
  64. // Values
  65. List<Double> listCountries = new ArrayList<>(10);
  66. List<Double> listSpeakers = new ArrayList<>(10);
  67. // set model
  68. String ln;
  69. while((ln = modelReader.readLine()) != null) {
  70. String[] vals = ln.split(",");
  71. listCountries.add(Double.valueOf(vals[0]));
  72. listSpeakers.add(Double.valueOf(vals[1]));
  73. listLanguages.add(vals[2]);
  74. }
  75. String[] categories = listLanguages.toArray(new String[0]);
  76. Double[] values1 = listCountries.toArray(new Double[0]);
  77. Double[] values2 = listSpeakers.toArray(new Double[0]);
  78. try (XWPFDocument doc = new XWPFDocument(argIS)) {
  79. XWPFChart chart = doc.getCharts().get(0);
  80. setBarData(chart, chartTitle, series, categories, values1, values2);
  81. chart = doc.getCharts().get(1);
  82. setColumnData(chart, "Column variant");
  83. // save the result
  84. try (OutputStream out = new FileOutputStream("bar-chart-demo-output.docx")) {
  85. doc.write(out);
  86. }
  87. }
  88. }
  89. System.out.println("Done");
  90. }
  91. private static void setBarData(XWPFChart 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, 0, 0));
  96. final String valuesDataRange = chart.formatRange(new CellRangeAddress(1, numOfPoints, 1, 1));
  97. final String valuesDataRange2 = chart.formatRange(new CellRangeAddress(1, numOfPoints, 2, 2));
  98. final XDDFDataSource<?> categoriesData = XDDFDataSourcesFactory.fromArray(categories, categoryDataRange, 0);
  99. final XDDFNumericalDataSource<? extends Number> valuesData = XDDFDataSourcesFactory.fromArray(values1, valuesDataRange, 1);
  100. values1[6] = 16.0; // if you ever want to change the underlying data
  101. final XDDFNumericalDataSource<? extends Number> valuesData2 = XDDFDataSourcesFactory.fromArray(values2, valuesDataRange2, 2);
  102. XDDFChartData.Series series1 = bar.getSeries(0);
  103. series1.replaceData(categoriesData, valuesData);
  104. series1.setTitle(series[0], chart.setSheetTitle(series[0], 0));
  105. XDDFChartData.Series series2 = bar.addSeries(categoriesData, valuesData2);
  106. series2.setTitle(series[1], chart.setSheetTitle(series[1], 1));
  107. chart.plot(bar);
  108. chart.setTitleText(chartTitle);
  109. chart.setTitleOverlay(false);
  110. }
  111. private static void setColumnData(XWPFChart chart, String chartTitle) {
  112. // Series Text
  113. List<XDDFChartData> series = chart.getChartSeries();
  114. XDDFBarChartData bar = (XDDFBarChartData) series.get(0);
  115. // in order to transform a bar chart into a column chart, you just need to change the bar direction
  116. bar.setBarDirection(BarDirection.COL);
  117. // looking for "Stacked Bar Chart"? uncomment the following line
  118. // bar.setBarGrouping(BarGrouping.STACKED);
  119. // additionally, you can adjust the axes
  120. bar.getCategoryAxis().setOrientation(AxisOrientation.MAX_MIN);
  121. bar.getValueAxes().get(0).setPosition(AxisPosition.TOP);
  122. }
  123. }