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.

XDDFChart.java 38KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105
  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.xddf.usermodel.chart;
  20. import static org.apache.poi.ooxml.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
  21. import java.io.IOException;
  22. import java.io.OutputStream;
  23. import java.util.ArrayList;
  24. import java.util.Collections;
  25. import java.util.HashMap;
  26. import java.util.LinkedList;
  27. import java.util.List;
  28. import java.util.Map;
  29. import java.util.Optional;
  30. import java.util.function.Function;
  31. import java.util.function.Predicate;
  32. import javax.xml.namespace.QName;
  33. import org.apache.poi.ooxml.POIXMLDocument;
  34. import org.apache.poi.ooxml.POIXMLDocumentPart;
  35. import org.apache.poi.ooxml.POIXMLException;
  36. import org.apache.poi.ooxml.POIXMLFactory;
  37. import org.apache.poi.ooxml.POIXMLRelation;
  38. import org.apache.poi.openxml4j.exceptions.InvalidFormatException;
  39. import org.apache.poi.openxml4j.exceptions.NotOfficeXmlFileException;
  40. import org.apache.poi.openxml4j.opc.PackagePart;
  41. import org.apache.poi.openxml4j.opc.PackageRelationship;
  42. import org.apache.poi.ss.util.CellRangeAddress;
  43. import org.apache.poi.ss.util.CellReference;
  44. import org.apache.poi.util.Beta;
  45. import org.apache.poi.util.Internal;
  46. import org.apache.poi.xddf.usermodel.XDDFShapeProperties;
  47. import org.apache.poi.xddf.usermodel.text.TextContainer;
  48. import org.apache.poi.xddf.usermodel.text.XDDFTextBody;
  49. import org.apache.poi.xssf.usermodel.XSSFCell;
  50. import org.apache.poi.xssf.usermodel.XSSFRow;
  51. import org.apache.poi.xssf.usermodel.XSSFSheet;
  52. import org.apache.poi.xssf.usermodel.XSSFWorkbook;
  53. import org.apache.xmlbeans.XmlException;
  54. import org.apache.xmlbeans.XmlOptions;
  55. import org.openxmlformats.schemas.drawingml.x2006.chart.CTArea3DChart;
  56. import org.openxmlformats.schemas.drawingml.x2006.chart.CTAreaChart;
  57. import org.openxmlformats.schemas.drawingml.x2006.chart.CTBar3DChart;
  58. import org.openxmlformats.schemas.drawingml.x2006.chart.CTBarChart;
  59. import org.openxmlformats.schemas.drawingml.x2006.chart.CTBoolean;
  60. import org.openxmlformats.schemas.drawingml.x2006.chart.CTCatAx;
  61. import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart;
  62. import org.openxmlformats.schemas.drawingml.x2006.chart.CTChartSpace;
  63. import org.openxmlformats.schemas.drawingml.x2006.chart.CTDateAx;
  64. import org.openxmlformats.schemas.drawingml.x2006.chart.CTDoughnutChart;
  65. import org.openxmlformats.schemas.drawingml.x2006.chart.CTExternalData;
  66. import org.openxmlformats.schemas.drawingml.x2006.chart.CTLine3DChart;
  67. import org.openxmlformats.schemas.drawingml.x2006.chart.CTLineChart;
  68. import org.openxmlformats.schemas.drawingml.x2006.chart.CTPie3DChart;
  69. import org.openxmlformats.schemas.drawingml.x2006.chart.CTPieChart;
  70. import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea;
  71. import org.openxmlformats.schemas.drawingml.x2006.chart.CTRadarChart;
  72. import org.openxmlformats.schemas.drawingml.x2006.chart.CTScatterChart;
  73. import org.openxmlformats.schemas.drawingml.x2006.chart.CTSerAx;
  74. import org.openxmlformats.schemas.drawingml.x2006.chart.CTSurface;
  75. import org.openxmlformats.schemas.drawingml.x2006.chart.CTSurface3DChart;
  76. import org.openxmlformats.schemas.drawingml.x2006.chart.CTSurfaceChart;
  77. import org.openxmlformats.schemas.drawingml.x2006.chart.CTTitle;
  78. import org.openxmlformats.schemas.drawingml.x2006.chart.CTValAx;
  79. import org.openxmlformats.schemas.drawingml.x2006.chart.CTView3D;
  80. import org.openxmlformats.schemas.drawingml.x2006.chart.ChartSpaceDocument;
  81. import org.openxmlformats.schemas.drawingml.x2006.main.CTShapeProperties;
  82. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextCharacterProperties;
  83. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraphProperties;
  84. @Beta
  85. public abstract class XDDFChart extends POIXMLDocumentPart implements TextContainer {
  86. /**
  87. * default width of chart in emu
  88. */
  89. public static final int DEFAULT_WIDTH = 500000;
  90. /**
  91. * default height of chart in emu
  92. */
  93. public static final int DEFAULT_HEIGHT = 500000;
  94. /**
  95. * default x-coordinate of chart in emu
  96. */
  97. public static final int DEFAULT_X = 10;
  98. /**
  99. * default y-coordinate value of chart in emu
  100. */
  101. public static final int DEFAULT_Y = 10;
  102. /**
  103. * Underlying workbook
  104. */
  105. private XSSFWorkbook workbook;
  106. private int chartIndex = 0;
  107. protected List<XDDFChartAxis> axes = new ArrayList<>();
  108. /**
  109. * Root element of the Chart part
  110. */
  111. protected final CTChartSpace chartSpace;
  112. /**
  113. * Construct a chart.
  114. */
  115. protected XDDFChart() {
  116. super();
  117. chartSpace = CTChartSpace.Factory.newInstance();
  118. chartSpace.addNewChart().addNewPlotArea();
  119. }
  120. /**
  121. * Construct a DrawingML chart from a package part.
  122. *
  123. * @param part
  124. * the package part holding the chart data, the content type must
  125. * be
  126. * {@code application/vnd.openxmlformats-officedocument.drawingml.chart+xml}
  127. * @since POI 3.14-Beta1
  128. */
  129. protected XDDFChart(PackagePart part) throws IOException, XmlException {
  130. super(part);
  131. chartSpace = ChartSpaceDocument.Factory.parse(part.getInputStream(), DEFAULT_XML_OPTIONS).getChartSpace();
  132. }
  133. /**
  134. * Return the underlying CTChartSpace bean, the root element of the Chart
  135. * part.
  136. *
  137. * @return the underlying CTChartSpace bean
  138. */
  139. @Internal
  140. public CTChartSpace getCTChartSpace() {
  141. return chartSpace;
  142. }
  143. /**
  144. * Return the underlying CTChart bean, within the Chart Space
  145. *
  146. * @return the underlying CTChart bean
  147. */
  148. @Internal
  149. public CTChart getCTChart() {
  150. return chartSpace.getChart();
  151. }
  152. /**
  153. * Return the underlying CTPlotArea bean, within the Chart
  154. *
  155. * @return the underlying CTPlotArea bean
  156. */
  157. @Internal
  158. protected CTPlotArea getCTPlotArea() {
  159. return getCTChart().getPlotArea();
  160. }
  161. /**
  162. * Clear all properties, as if a new instance had just been created.
  163. * @since POI 4.1.2
  164. */
  165. public void clear() {
  166. axes.clear();
  167. seriesCount = 0;
  168. if (workbook != null) {
  169. workbook.removeSheetAt(0);
  170. workbook.createSheet();
  171. }
  172. getCTChart().set(CTChart.Factory.newInstance());
  173. getCTChart().addNewPlotArea();
  174. }
  175. /**
  176. * @return true if only visible cells will be present on the chart, false
  177. * otherwise
  178. */
  179. public boolean isPlotOnlyVisibleCells() {
  180. if (getCTChart().isSetPlotVisOnly()) {
  181. return getCTChart().getPlotVisOnly().getVal();
  182. } else {
  183. return false;
  184. }
  185. }
  186. /**
  187. * @param only
  188. * a flag specifying if only visible cells should be present on
  189. * the chart
  190. */
  191. public void setPlotOnlyVisibleCells(boolean only) {
  192. if (!getCTChart().isSetPlotVisOnly()) {
  193. getCTChart().setPlotVisOnly(CTBoolean.Factory.newInstance());
  194. }
  195. getCTChart().getPlotVisOnly().setVal(only);
  196. }
  197. public void setFloor(int thickness) {
  198. if (!getCTChart().isSetFloor()) {
  199. getCTChart().setFloor(CTSurface.Factory.newInstance());
  200. }
  201. getCTChart().getFloor().getThickness().setVal(thickness);
  202. }
  203. public void setBackWall(int thickness) {
  204. if (!getCTChart().isSetBackWall()) {
  205. getCTChart().setBackWall(CTSurface.Factory.newInstance());
  206. }
  207. getCTChart().getBackWall().getThickness().setVal(thickness);
  208. }
  209. public void setSideWall(int thickness) {
  210. if (!getCTChart().isSetSideWall()) {
  211. getCTChart().setSideWall(CTSurface.Factory.newInstance());
  212. }
  213. getCTChart().getSideWall().getThickness().setVal(thickness);
  214. }
  215. public void setAutoTitleDeleted(boolean deleted) {
  216. if (!getCTChart().isSetAutoTitleDeleted()) {
  217. getCTChart().setAutoTitleDeleted(CTBoolean.Factory.newInstance());
  218. }
  219. getCTChart().getAutoTitleDeleted().setVal(deleted);
  220. if (deleted && getCTChart().isSetTitle()) {
  221. getCTChart().unsetTitle();
  222. }
  223. }
  224. /**
  225. * @since 4.0.1
  226. *
  227. */
  228. public void displayBlanksAs(DisplayBlanks as) {
  229. if (as == null){
  230. if (getCTChart().isSetDispBlanksAs()) {
  231. getCTChart().unsetDispBlanksAs();
  232. }
  233. } else {
  234. if (getCTChart().isSetDispBlanksAs()) {
  235. getCTChart().getDispBlanksAs().setVal(as.underlying);
  236. } else {
  237. getCTChart().addNewDispBlanksAs().setVal(as.underlying);
  238. }
  239. }
  240. }
  241. /**
  242. * @since 4.0.1
  243. */
  244. public Boolean getTitleOverlay() {
  245. if (getCTChart().isSetTitle()) {
  246. CTTitle title = getCTChart().getTitle();
  247. if (title.isSetOverlay()) {
  248. return title.getOverlay().getVal();
  249. }
  250. }
  251. return null;
  252. }
  253. /**
  254. * @since 4.0.1
  255. */
  256. public void setTitleOverlay(boolean overlay) {
  257. if (!getCTChart().isSetTitle()) {
  258. getCTChart().addNewTitle();
  259. }
  260. new XDDFTitle(this, getCTChart().getTitle()).setOverlay(overlay);
  261. }
  262. /**
  263. * Sets the title text as a static string.
  264. *
  265. * @param text
  266. * to use as new title
  267. * @since 4.0.1
  268. */
  269. public void setTitleText(String text) {
  270. if (!getCTChart().isSetTitle()) {
  271. getCTChart().addNewTitle();
  272. }
  273. new XDDFTitle(this, getCTChart().getTitle()).setText(text);
  274. }
  275. /**
  276. * @since 4.0.1
  277. */
  278. public XDDFTitle getTitle() {
  279. if (getCTChart().isSetTitle()) {
  280. return new XDDFTitle(this, getCTChart().getTitle());
  281. } else {
  282. return null;
  283. }
  284. }
  285. /**
  286. * Remove the chart title.
  287. * @since POI 5.0.0
  288. */
  289. public void removeTitle() {
  290. setAutoTitleDeleted(true);
  291. }
  292. /**
  293. * Get or Add chart 3D view into chart
  294. *
  295. * @return this method will add 3D view
  296. */
  297. public XDDFView3D getOrAddView3D() {
  298. CTView3D view3D;
  299. if (getCTChart().isSetView3D()) {
  300. view3D = getCTChart().getView3D();
  301. } else {
  302. view3D = getCTChart().addNewView3D();
  303. }
  304. return new XDDFView3D(view3D);
  305. }
  306. /**
  307. * Get the chart title body if there is one, i.e. title is set and is not a
  308. * formula.
  309. *
  310. * @return text body or null, if title is a formula or no title is set.
  311. */
  312. @Beta
  313. public XDDFTextBody getFormattedTitle() {
  314. if (!getCTChart().isSetTitle()) {
  315. return null;
  316. }
  317. return new XDDFTitle(this, getCTChart().getTitle()).getBody();
  318. }
  319. @Override
  320. public <R> Optional<R> findDefinedParagraphProperty(Predicate<CTTextParagraphProperties> isSet,
  321. Function<CTTextParagraphProperties, R> getter) {
  322. // TODO Auto-generated method stub
  323. return Optional.empty();
  324. }
  325. @Override
  326. public <R> Optional<R> findDefinedRunProperty(Predicate<CTTextCharacterProperties> isSet,
  327. Function<CTTextCharacterProperties, R> getter) {
  328. // TODO Auto-generated method stub
  329. return Optional.empty();
  330. }
  331. public XDDFShapeProperties getOrAddShapeProperties() {
  332. CTPlotArea plotArea = getCTPlotArea();
  333. CTShapeProperties properties;
  334. if (plotArea.isSetSpPr()) {
  335. properties = plotArea.getSpPr();
  336. } else {
  337. properties = plotArea.addNewSpPr();
  338. }
  339. return new XDDFShapeProperties(properties);
  340. }
  341. public void deleteShapeProperties() {
  342. if (getCTPlotArea().isSetSpPr()) {
  343. getCTPlotArea().unsetSpPr();
  344. }
  345. }
  346. public XDDFChartLegend getOrAddLegend() {
  347. return new XDDFChartLegend(getCTChart());
  348. }
  349. public void deleteLegend() {
  350. if (getCTChart().isSetLegend()) {
  351. getCTChart().unsetLegend();
  352. }
  353. }
  354. public XDDFManualLayout getOrAddManualLayout() {
  355. return new XDDFManualLayout(getCTPlotArea());
  356. }
  357. private long seriesCount = 0;
  358. protected long incrementSeriesCount() {
  359. return seriesCount++;
  360. }
  361. public void plot(XDDFChartData data) {
  362. XSSFSheet sheet = getSheet();
  363. for (int idx = 0; idx < data.getSeriesCount(); idx++) {
  364. XDDFChartData.Series series = data.getSeries(idx);
  365. series.plot();
  366. XDDFDataSource<?> categoryDS = series.getCategoryData();
  367. XDDFNumericalDataSource<? extends Number> valuesDS = series.getValuesData();
  368. if (categoryDS != null && !categoryDS.isCellRange() && !categoryDS.isLiteral() &&
  369. valuesDS != null && !valuesDS.isCellRange() && !valuesDS.isLiteral()) {
  370. fillSheet(sheet, categoryDS, valuesDS);
  371. }
  372. // otherwise let's assume the data is already in the sheet
  373. }
  374. }
  375. public List<XDDFChartData> getChartSeries() {
  376. List<XDDFChartData> series = new LinkedList<>();
  377. CTPlotArea plotArea = getCTPlotArea();
  378. Map<Long, XDDFChartAxis> categories = getCategoryAxes();
  379. Map<Long, XDDFValueAxis> values = getValueAxes();
  380. for (int i = 0; i < plotArea.sizeOfAreaChartArray(); i++) {
  381. CTAreaChart areaChart = plotArea.getAreaChartArray(i);
  382. series.add(new XDDFAreaChartData(this, areaChart, categories, values));
  383. }
  384. for (int i = 0; i < plotArea.sizeOfArea3DChartArray(); i++) {
  385. CTArea3DChart areaChart = plotArea.getArea3DChartArray(i);
  386. series.add(new XDDFArea3DChartData(this, areaChart, categories, values));
  387. }
  388. for (int i = 0; i < plotArea.sizeOfBarChartArray(); i++) {
  389. CTBarChart barChart = plotArea.getBarChartArray(i);
  390. series.add(new XDDFBarChartData(this, barChart, categories, values));
  391. }
  392. for (int i = 0; i < plotArea.sizeOfBar3DChartArray(); i++) {
  393. CTBar3DChart barChart = plotArea.getBar3DChartArray(i);
  394. series.add(new XDDFBar3DChartData(this, barChart, categories, values));
  395. }
  396. for (int i = 0; i < plotArea.sizeOfDoughnutChartArray(); i++) {
  397. CTDoughnutChart doughnutChart = plotArea.getDoughnutChartArray(i);
  398. series.add(new XDDFDoughnutChartData(this, doughnutChart));
  399. }
  400. for (int i = 0; i < plotArea.sizeOfLineChartArray(); i++) {
  401. CTLineChart lineChart = plotArea.getLineChartArray(i);
  402. series.add(new XDDFLineChartData(this, lineChart, categories, values));
  403. }
  404. for (int i = 0; i < plotArea.sizeOfLine3DChartArray(); i++) {
  405. CTLine3DChart lineChart = plotArea.getLine3DChartArray(i);
  406. series.add(new XDDFLine3DChartData(this, lineChart, categories, values));
  407. }
  408. for (int i = 0; i < plotArea.sizeOfPieChartArray(); i++) {
  409. CTPieChart pieChart = plotArea.getPieChartArray(i);
  410. series.add(new XDDFPieChartData(this, pieChart));
  411. }
  412. for (int i = 0; i < plotArea.sizeOfPie3DChartArray(); i++) {
  413. CTPie3DChart pieChart = plotArea.getPie3DChartArray(i);
  414. series.add(new XDDFPie3DChartData(this, pieChart));
  415. }
  416. for (int i = 0; i < plotArea.sizeOfRadarChartArray(); i++) {
  417. CTRadarChart radarChart = plotArea.getRadarChartArray(i);
  418. series.add(new XDDFRadarChartData(this, radarChart, categories, values));
  419. }
  420. for (int i = 0; i < plotArea.sizeOfScatterChartArray(); i++) {
  421. CTScatterChart scatterChart = plotArea.getScatterChartArray(i);
  422. series.add(new XDDFScatterChartData(this, scatterChart, categories, values));
  423. }
  424. for (int i = 0; i < plotArea.sizeOfSurfaceChartArray(); i++) {
  425. CTSurfaceChart surfaceChart = plotArea.getSurfaceChartArray(i);
  426. series.add(new XDDFSurfaceChartData(this, surfaceChart, categories, values));
  427. }
  428. for (int i = 0; i < plotArea.sizeOfSurface3DChartArray(); i++) {
  429. CTSurface3DChart surfaceChart = plotArea.getSurface3DChartArray(i);
  430. series.add(new XDDFSurface3DChartData(this, surfaceChart, categories, values));
  431. }
  432. // TODO repeat above code for missing charts: Bubble, OfPie and Stock
  433. seriesCount = series.size();
  434. return series;
  435. }
  436. /**
  437. * Clear all chart series, as if a new instance had just been created.
  438. * @since POI 4.1.2
  439. */
  440. public void clearChartSeries() {
  441. CTPlotArea plotArea = getCTPlotArea();
  442. for (int i = plotArea.sizeOfAreaChartArray(); i > 0; i--) {
  443. plotArea.removeAreaChart(i - 1);
  444. }
  445. for (int i = plotArea.sizeOfArea3DChartArray(); i > 0; i--) {
  446. plotArea.removeArea3DChart(i - 1);
  447. }
  448. for (int i = plotArea.sizeOfBarChartArray(); i > 0; i--) {
  449. plotArea.removeBarChart(i - 1);
  450. }
  451. for (int i = plotArea.sizeOfBar3DChartArray(); i > 0; i--) {
  452. plotArea.removeBar3DChart(i - 1);
  453. }
  454. for (int i = plotArea.sizeOfBubbleChartArray(); i > 0; i--) {
  455. plotArea.removeBubbleChart(i - 1);
  456. }
  457. for (int i = plotArea.sizeOfDoughnutChartArray(); i > 0; i--) {
  458. plotArea.removeDoughnutChart(i - 1);
  459. }
  460. for (int i = plotArea.sizeOfLineChartArray(); i > 0; i--) {
  461. plotArea.removeLineChart(i - 1);
  462. }
  463. for (int i = plotArea.sizeOfLine3DChartArray(); i > 0; i--) {
  464. plotArea.removeLine3DChart(i - 1);
  465. }
  466. for (int i = plotArea.sizeOfOfPieChartArray(); i > 0; i--) {
  467. plotArea.removeOfPieChart(i - 1);
  468. }
  469. for (int i = plotArea.sizeOfPieChartArray(); i > 0; i--) {
  470. plotArea.removePieChart(i - 1);
  471. }
  472. for (int i = plotArea.sizeOfPie3DChartArray(); i > 0; i--) {
  473. plotArea.removePie3DChart(i - 1);
  474. }
  475. for (int i = plotArea.sizeOfRadarChartArray(); i > 0; i--) {
  476. plotArea.removeRadarChart(i - 1);
  477. }
  478. for (int i = plotArea.sizeOfScatterChartArray(); i > 0; i--) {
  479. plotArea.removeScatterChart(i - 1);
  480. }
  481. for (int i = plotArea.sizeOfStockChartArray(); i > 0; i--) {
  482. plotArea.removeStockChart(i - 1);
  483. }
  484. for (int i = plotArea.sizeOfSurfaceChartArray(); i > 0; i--) {
  485. plotArea.removeSurfaceChart(i - 1);
  486. }
  487. for (int i = plotArea.sizeOfSurface3DChartArray(); i > 0; i--) {
  488. plotArea.removeSurface3DChart(i - 1);
  489. }
  490. }
  491. private Map<Long, XDDFChartAxis> getCategoryAxes() {
  492. CTPlotArea plotArea = getCTPlotArea();
  493. int sizeOfArray = plotArea.sizeOfCatAxArray();
  494. Map<Long, XDDFChartAxis> axesMap = new HashMap<>(sizeOfArray);
  495. for (int i = 0; i < sizeOfArray; i++) {
  496. CTCatAx category = plotArea.getCatAxArray(i);
  497. axesMap.put(category.getAxId().getVal(), new XDDFCategoryAxis(category));
  498. }
  499. return axesMap;
  500. }
  501. private Map<Long, XDDFValueAxis> getValueAxes() {
  502. CTPlotArea plotArea = getCTPlotArea();
  503. int sizeOfArray = plotArea.sizeOfValAxArray();
  504. Map<Long, XDDFValueAxis> axesMap = new HashMap<>(sizeOfArray);
  505. for (int i = 0; i < sizeOfArray; i++) {
  506. CTValAx values = plotArea.getValAxArray(i);
  507. axesMap.put(values.getAxId().getVal(), new XDDFValueAxis(values));
  508. }
  509. return axesMap;
  510. }
  511. public XDDFValueAxis createValueAxis(AxisPosition pos) {
  512. XDDFValueAxis valueAxis = new XDDFValueAxis(getCTPlotArea(), pos);
  513. addAxis(valueAxis);
  514. return valueAxis;
  515. }
  516. /**
  517. * this method will return series axis with specified position
  518. *
  519. * @param pos axis position Left, Right, Top, Bottom
  520. * @return series axis with specified position
  521. */
  522. public XDDFSeriesAxis createSeriesAxis(AxisPosition pos) {
  523. XDDFSeriesAxis seriesAxis = new XDDFSeriesAxis(getCTPlotArea(), pos);
  524. addAxis(seriesAxis);
  525. return seriesAxis;
  526. }
  527. public XDDFCategoryAxis createCategoryAxis(AxisPosition pos) {
  528. XDDFCategoryAxis categoryAxis = new XDDFCategoryAxis(getCTPlotArea(), pos);
  529. addAxis(categoryAxis);
  530. return categoryAxis;
  531. }
  532. public XDDFDateAxis createDateAxis(AxisPosition pos) {
  533. XDDFDateAxis dateAxis = new XDDFDateAxis(getCTPlotArea(), pos);
  534. addAxis(dateAxis);
  535. return dateAxis;
  536. }
  537. private void addAxis(XDDFChartAxis newAxis) {
  538. if (axes.size() == 1) {
  539. XDDFChartAxis axis = axes.get(0);
  540. axis.crossAxis(newAxis);
  541. newAxis.crossAxis(axis);
  542. axis.setCrosses(AxisCrosses.AUTO_ZERO);
  543. newAxis.setCrosses(AxisCrosses.AUTO_ZERO);
  544. }
  545. axes.add(newAxis);
  546. }
  547. /**
  548. * this method will return specified chart data with category and series values
  549. *
  550. * @param type chart type
  551. * @param category category values of chart
  552. * @param values series values of chart
  553. * @return specified chart data.
  554. */
  555. public XDDFChartData createData(ChartTypes type, XDDFChartAxis category, XDDFValueAxis values) {
  556. Map<Long, XDDFChartAxis> categories = null;
  557. Map<Long, XDDFValueAxis> mapValues = null;
  558. if (ChartTypes.PIE != type && ChartTypes.PIE3D != type && ChartTypes.DOUGHNUT != type) {
  559. categories = Collections.singletonMap(category.getId(), category);
  560. mapValues = Collections.singletonMap(values.getId(), values);
  561. }
  562. final CTPlotArea plotArea = getCTPlotArea();
  563. switch (type) {
  564. case AREA:
  565. return new XDDFAreaChartData(this, plotArea.addNewAreaChart(), categories, mapValues);
  566. case AREA3D:
  567. return new XDDFArea3DChartData(this, plotArea.addNewArea3DChart(), categories, mapValues);
  568. case BAR:
  569. return new XDDFBarChartData(this, plotArea.addNewBarChart(), categories, mapValues);
  570. case BAR3D:
  571. return new XDDFBar3DChartData(this, plotArea.addNewBar3DChart(), categories, mapValues);
  572. case DOUGHNUT:
  573. return new XDDFDoughnutChartData(this, plotArea.addNewDoughnutChart());
  574. case LINE:
  575. return new XDDFLineChartData(this, plotArea.addNewLineChart(), categories, mapValues);
  576. case LINE3D:
  577. return new XDDFLine3DChartData(this, plotArea.addNewLine3DChart(), categories, mapValues);
  578. case PIE:
  579. return new XDDFPieChartData(this, plotArea.addNewPieChart());
  580. case PIE3D:
  581. return new XDDFPie3DChartData(this, plotArea.addNewPie3DChart());
  582. case RADAR:
  583. return new XDDFRadarChartData(this, plotArea.addNewRadarChart(), categories, mapValues);
  584. case SCATTER:
  585. return new XDDFScatterChartData(this, plotArea.addNewScatterChart(), categories, mapValues);
  586. case SURFACE:
  587. return new XDDFSurfaceChartData(this, plotArea.addNewSurfaceChart(), categories, mapValues);
  588. case SURFACE3D:
  589. return new XDDFSurface3DChartData(this, plotArea.addNewSurface3DChart(), categories, mapValues);
  590. // TODO repeat above code for missing charts: Bubble, OfPie and Stock
  591. default:
  592. return null;
  593. }
  594. }
  595. public List<? extends XDDFChartAxis> getAxes() {
  596. if (axes.isEmpty() && hasAxes()) {
  597. parseAxes();
  598. }
  599. return axes;
  600. }
  601. private boolean hasAxes() {
  602. CTPlotArea ctPlotArea = getCTPlotArea();
  603. int totalAxisCount = ctPlotArea.sizeOfValAxArray() + ctPlotArea.sizeOfCatAxArray() + ctPlotArea
  604. .sizeOfDateAxArray() + ctPlotArea.sizeOfSerAxArray();
  605. return totalAxisCount > 0;
  606. }
  607. private void parseAxes() {
  608. for (CTCatAx catAx : getCTPlotArea().getCatAxArray()) {
  609. axes.add(new XDDFCategoryAxis(catAx));
  610. }
  611. for (CTDateAx dateAx : getCTPlotArea().getDateAxArray()) {
  612. axes.add(new XDDFDateAxis(dateAx));
  613. }
  614. for (CTSerAx serAx : getCTPlotArea().getSerAxArray()) {
  615. axes.add(new XDDFSeriesAxis(serAx));
  616. }
  617. for (CTValAx valAx : getCTPlotArea().getValAxArray()) {
  618. axes.add(new XDDFValueAxis(valAx));
  619. }
  620. }
  621. /**
  622. * Set value range (basic Axis Options)
  623. *
  624. * @param axisIndex
  625. * 0 - primary axis, 1 - secondary axis
  626. * @param minimum
  627. * minimum value; Double.NaN - automatic; null - no change
  628. * @param maximum
  629. * maximum value; Double.NaN - automatic; null - no change
  630. * @param majorUnit
  631. * major unit value; Double.NaN - automatic; null - no change
  632. * @param minorUnit
  633. * minor unit value; Double.NaN - automatic; null - no change
  634. */
  635. public void setValueRange(int axisIndex, Double minimum, Double maximum, Double majorUnit, Double minorUnit) {
  636. XDDFChartAxis axis = getAxes().get(axisIndex);
  637. if (axis == null) {
  638. return;
  639. }
  640. if (minimum != null) {
  641. axis.setMinimum(minimum);
  642. }
  643. if (maximum != null) {
  644. axis.setMaximum(maximum);
  645. }
  646. if (majorUnit != null) {
  647. axis.setMajorUnit(majorUnit);
  648. }
  649. if (minorUnit != null) {
  650. axis.setMinorUnit(minorUnit);
  651. }
  652. }
  653. /**
  654. * method to create relationship with embedded part for example writing xlsx
  655. * file stream into output stream
  656. *
  657. * @param chartRelation
  658. * relationship object
  659. * @param chartFactory
  660. * ChartFactory object
  661. * @param chartIndex
  662. * index used to suffix on file
  663. * @return return relation part which used to write relation in .rels file
  664. * and get relation id
  665. * @since POI 4.0.0
  666. */
  667. public PackageRelationship createRelationshipInChart(POIXMLRelation chartRelation, POIXMLFactory chartFactory,
  668. int chartIndex) {
  669. POIXMLDocumentPart documentPart =
  670. createRelationship(chartRelation, chartFactory, chartIndex, true).getDocumentPart();
  671. return addRelation(null, chartRelation, documentPart).getRelationship();
  672. }
  673. /**
  674. * if embedded part was null then create new part
  675. *
  676. * @param chartWorkbookRelation
  677. * chart workbook relation object
  678. * @param chartFactory
  679. * factory object of POIXMLFactory (XWPFFactory/XSLFFactory)
  680. * @return return the new package part
  681. * @since POI 4.0.0
  682. */
  683. private PackagePart createWorksheetPart(POIXMLRelation chartWorkbookRelation, POIXMLFactory chartFactory)
  684. throws InvalidFormatException {
  685. PackageRelationship xlsx = createRelationshipInChart(chartWorkbookRelation, chartFactory, chartIndex);
  686. setExternalId(xlsx.getId());
  687. return getTargetPart(xlsx);
  688. }
  689. /**
  690. * this method write the XSSFWorkbook object data into embedded excel file
  691. *
  692. * @param workbook XSSFworkbook object
  693. * @since POI 4.0.0
  694. */
  695. public void saveWorkbook(XSSFWorkbook workbook) throws IOException, InvalidFormatException {
  696. PackagePart worksheetPart = getWorksheetPart();
  697. if (worksheetPart == null) {
  698. POIXMLRelation chartWorkbookRelation = getChartWorkbookRelation();
  699. POIXMLFactory chartFactory = getChartFactory();
  700. if (chartWorkbookRelation != null && chartFactory != null) {
  701. worksheetPart = createWorksheetPart(chartWorkbookRelation, chartFactory);
  702. } else {
  703. throw new InvalidFormatException("unable to determine chart relations");
  704. }
  705. }
  706. try (OutputStream xlsOut = worksheetPart.getOutputStream()) {
  707. setWorksheetPartCommitted();
  708. workbook.write(xlsOut);
  709. }
  710. }
  711. /**
  712. *
  713. * @return the chart relation in the implementing subclass.
  714. * @since POI 4.0.0
  715. */
  716. protected abstract POIXMLRelation getChartRelation();
  717. /**
  718. *
  719. * @return the chart workbook relation in the implementing subclass.
  720. * @since POI 4.0.0
  721. */
  722. protected abstract POIXMLRelation getChartWorkbookRelation();
  723. /**
  724. *
  725. * @return the chart factory in the implementing subclass.
  726. * @since POI 4.0.0
  727. */
  728. protected abstract POIXMLFactory getChartFactory();
  729. /**
  730. * this method writes the data into sheet
  731. *
  732. * @param sheet
  733. * sheet of embedded excel
  734. * @param categoryData
  735. * category values
  736. * @param valuesData
  737. * data values
  738. * @since POI 4.0.0
  739. */
  740. protected void fillSheet(XSSFSheet sheet, XDDFDataSource<?> categoryData, XDDFNumericalDataSource<?> valuesData) {
  741. int numOfPoints = categoryData.getPointCount();
  742. for (int i = 0; i < numOfPoints; i++) {
  743. XSSFRow row = getRow(sheet, i + 1); // first row is for title
  744. Object category = categoryData.getPointAt(i);
  745. if (category != null) {
  746. getCell(row, categoryData.getColIndex()).setCellValue(category.toString());
  747. }
  748. Number value = valuesData.getPointAt(i);
  749. if (value != null) {
  750. getCell(row, valuesData.getColIndex()).setCellValue(value.doubleValue());
  751. }
  752. }
  753. }
  754. /**
  755. * this method return row on given index if row is null then create new row
  756. *
  757. * @param sheet
  758. * current sheet object
  759. * @param index
  760. * index of current row
  761. * @return this method return sheet row on given index
  762. * @since POI 4.0.0
  763. */
  764. private XSSFRow getRow(XSSFSheet sheet, int index) {
  765. XSSFRow row = sheet.getRow(index);
  766. if (row == null) {
  767. return sheet.createRow(index);
  768. } else {
  769. return row;
  770. }
  771. }
  772. /**
  773. * this method return cell on given index if cell is null then create new
  774. * cell
  775. *
  776. * @param row
  777. * current row object
  778. * @param index
  779. * index of current cell
  780. * @return this method return sheet cell on given index
  781. * @since POI 4.0.0
  782. */
  783. private XSSFCell getCell(XSSFRow row, int index) {
  784. XSSFCell cell = row.getCell(index);
  785. if (cell == null) {
  786. return row.createCell(index);
  787. } else {
  788. return cell;
  789. }
  790. }
  791. /**
  792. * import content from other chart to created chart
  793. *
  794. * @param other
  795. * chart object
  796. * @since POI 4.0.0
  797. */
  798. public void importContent(XDDFChart other) {
  799. getCTChartSpace().set(other.getCTChartSpace());
  800. }
  801. /**
  802. * save chart xml
  803. */
  804. @Override
  805. protected void commit() throws IOException {
  806. XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
  807. xmlOptions.setSaveSyntheticDocumentElement(
  808. new QName(CTChartSpace.type.getName().getNamespaceURI(), "chartSpace", "c"));
  809. if (workbook != null) {
  810. try {
  811. saveWorkbook(workbook);
  812. } catch (InvalidFormatException e) {
  813. throw new POIXMLException(e);
  814. }
  815. }
  816. PackagePart part = getPackagePart();
  817. try (OutputStream out = part.getOutputStream()) {
  818. chartSpace.save(out, xmlOptions);
  819. }
  820. }
  821. /**
  822. * set sheet title in excel file
  823. *
  824. * @param title
  825. * title of sheet
  826. * @param column
  827. * column index
  828. * @return return cell reference
  829. * @since POI 4.0.0
  830. */
  831. public CellReference setSheetTitle(String title, int column) {
  832. XSSFSheet sheet = getSheet();
  833. if (sheet == null) {
  834. return null;
  835. }
  836. XSSFRow row = getRow(sheet, 0);
  837. XSSFCell cell = getCell(row, column);
  838. cell.setCellValue(title);
  839. return new CellReference(sheet.getSheetName(), 0, column, true, true);
  840. }
  841. /**
  842. * @since POI 4.0.0
  843. */
  844. public String formatRange(CellRangeAddress range) {
  845. final XSSFSheet sheet = getSheet();
  846. return (sheet == null) ? null : range.formatAsString(sheet.getSheetName(), true);
  847. }
  848. /**
  849. * get sheet object of embedded excel file
  850. *
  851. * @return excel sheet object
  852. * @since POI 4.0.0
  853. */
  854. private XSSFSheet getSheet() {
  855. try {
  856. return getWorkbook().getSheetAt(0);
  857. } catch (InvalidFormatException | IOException ignored) {
  858. return null;
  859. }
  860. }
  861. /**
  862. * this method is used to get worksheet part if call is from saveworkbook
  863. * method then check isCommitted isCommitted variable shows that we are
  864. * writing xssfworkbook object into output stream of embedded part
  865. *
  866. * @return returns the packagepart of embedded file
  867. * @since POI 4.0.0
  868. */
  869. private PackagePart getWorksheetPart() throws InvalidFormatException {
  870. for (RelationPart part : getRelationParts()) {
  871. if (POIXMLDocument.PACK_OBJECT_REL_TYPE.equals(part.getRelationship().getRelationshipType())) {
  872. return getTargetPart(part.getRelationship());
  873. }
  874. }
  875. return null;
  876. }
  877. private void setWorksheetPartCommitted() {
  878. for (RelationPart part : getRelationParts()) {
  879. if (POIXMLDocument.PACK_OBJECT_REL_TYPE.equals(part.getRelationship().getRelationshipType())) {
  880. part.getDocumentPart().setCommitted(true);
  881. break;
  882. }
  883. }
  884. }
  885. /**
  886. * @return returns the workbook object of embedded excel file
  887. * @since POI 4.0.0
  888. */
  889. public XSSFWorkbook getWorkbook() throws IOException, InvalidFormatException {
  890. if (workbook == null) {
  891. try {
  892. PackagePart worksheetPart = getWorksheetPart();
  893. if (worksheetPart == null) {
  894. workbook = new XSSFWorkbook();
  895. workbook.createSheet();
  896. } else {
  897. workbook = new XSSFWorkbook(worksheetPart.getInputStream());
  898. }
  899. } catch (NotOfficeXmlFileException e) {
  900. workbook = new XSSFWorkbook();
  901. workbook.createSheet();
  902. }
  903. }
  904. return workbook;
  905. }
  906. /**
  907. * while reading chart from template file then we need to parse and store
  908. * embedded excel file in chart object show that we can modify value
  909. * according to use
  910. *
  911. * @param workbook
  912. * workbook object which we read from chart embedded part
  913. * @since POI 4.0.0
  914. */
  915. public void setWorkbook(XSSFWorkbook workbook) {
  916. this.workbook = workbook;
  917. }
  918. /**
  919. * set the relation id of embedded excel relation id into external data
  920. * relation tag
  921. *
  922. * @param id
  923. * relation id of embedded excel relation id into external data
  924. * relation tag
  925. * @since POI 4.0.0
  926. */
  927. public void setExternalId(String id) {
  928. CTChartSpace ctChartSpace = getCTChartSpace();
  929. CTExternalData externalData = ctChartSpace.isSetExternalData()
  930. ? ctChartSpace.getExternalData()
  931. : ctChartSpace.addNewExternalData();
  932. externalData.setId(id);
  933. }
  934. /**
  935. * @return method return chart index
  936. * @since POI 4.0.0
  937. */
  938. protected int getChartIndex() {
  939. return chartIndex;
  940. }
  941. /**
  942. * Set chart index which can be used for relation part.
  943. *
  944. * @param chartIndex
  945. * chart index which can be used for relation part.
  946. */
  947. public void setChartIndex(int chartIndex) {
  948. this.chartIndex = chartIndex;
  949. }
  950. /**
  951. * Replace references to the sheet name in the data supporting the chart.
  952. *
  953. * @param newSheet
  954. * sheet to be used in the data references.
  955. *
  956. * @since POI 5.1.0
  957. */
  958. public void replaceReferences(XSSFSheet newSheet) {
  959. for (XDDFChartData data : getChartSeries()) {
  960. for (XDDFChartData.Series series : data.series) {
  961. XDDFDataSource<?> newCategory = series.categoryData;
  962. XDDFNumericalDataSource<? extends Number> newValues = series.valuesData;
  963. try {
  964. if (series.categoryData != null && series.categoryData.isReference()) {
  965. String ref = series.categoryData.getDataRangeReference();
  966. CellRangeAddress rangeAddress = CellRangeAddress.valueOf(ref.substring(ref.indexOf('!') + 1));
  967. newCategory = series.categoryData.isNumeric()
  968. ? XDDFDataSourcesFactory.fromNumericCellRange(newSheet, rangeAddress)
  969. : XDDFDataSourcesFactory.fromStringCellRange(newSheet, rangeAddress);
  970. if (newCategory.isNumeric()) {
  971. ((XDDFNumericalDataSource<? extends Number>) newCategory).setFormatCode(series.categoryData.getFormatCode());
  972. }
  973. }
  974. if (series.valuesData!= null && series.valuesData.isReference()) {
  975. String ref = series.valuesData.getDataRangeReference();
  976. CellRangeAddress rangeAddress = CellRangeAddress.valueOf(ref.substring(ref.indexOf('!') + 1));
  977. newValues = XDDFDataSourcesFactory.fromNumericCellRange(newSheet, rangeAddress);
  978. newValues.setFormatCode(series.valuesData.getFormatCode());
  979. }
  980. } catch (IllegalArgumentException iae) {
  981. // keep old values when cell range cannot be parsed
  982. }
  983. series.replaceData(newCategory, newValues);
  984. series.plot();
  985. }
  986. }
  987. }
  988. }