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.

XSSFChart.java 12KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456
  1. /* ====================================================================
  2. Licensed to the Apache Software Foundation (ASF) under one or more
  3. contributor license agreements. See the NOTICE file distributed with
  4. this work for additional information regarding copyright ownership.
  5. The ASF licenses this file to You under the Apache License, Version 2.0
  6. (the "License"); you may not use this file except in compliance with
  7. the License. You may obtain a copy of the License at
  8. http://www.apache.org/licenses/LICENSE-2.0
  9. Unless required by applicable law or agreed to in writing, software
  10. distributed under the License is distributed on an "AS IS" BASIS,
  11. WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  12. See the License for the specific language governing permissions and
  13. limitations under the License.
  14. ==================================================================== */
  15. package org.apache.poi.xssf.usermodel;
  16. import static org.apache.poi.POIXMLTypeLoader.DEFAULT_XML_OPTIONS;
  17. import java.io.IOException;
  18. import java.io.OutputStream;
  19. import java.util.ArrayList;
  20. import java.util.List;
  21. import javax.xml.namespace.QName;
  22. import org.apache.poi.POIXMLDocumentPart;
  23. import org.apache.poi.openxml4j.opc.PackagePart;
  24. import org.apache.poi.ss.usermodel.Chart;
  25. import org.apache.poi.ss.usermodel.charts.AxisPosition;
  26. import org.apache.poi.ss.usermodel.charts.ChartAxis;
  27. import org.apache.poi.ss.usermodel.charts.ChartAxisFactory;
  28. import org.apache.poi.ss.usermodel.charts.ChartData;
  29. import org.apache.poi.util.Internal;
  30. import org.apache.poi.util.Removal;
  31. import org.apache.poi.xssf.usermodel.charts.XSSFCategoryAxis;
  32. import org.apache.poi.xssf.usermodel.charts.XSSFChartAxis;
  33. import org.apache.poi.xssf.usermodel.charts.XSSFChartDataFactory;
  34. import org.apache.poi.xssf.usermodel.charts.XSSFChartLegend;
  35. import org.apache.poi.xssf.usermodel.charts.XSSFManualLayout;
  36. import org.apache.poi.xssf.usermodel.charts.XSSFValueAxis;
  37. import org.apache.xmlbeans.XmlException;
  38. import org.apache.xmlbeans.XmlObject;
  39. import org.apache.xmlbeans.XmlOptions;
  40. import org.openxmlformats.schemas.drawingml.x2006.chart.CTCatAx;
  41. import org.openxmlformats.schemas.drawingml.x2006.chart.CTChart;
  42. import org.openxmlformats.schemas.drawingml.x2006.chart.CTChartSpace;
  43. import org.openxmlformats.schemas.drawingml.x2006.chart.CTPageMargins;
  44. import org.openxmlformats.schemas.drawingml.x2006.chart.CTPlotArea;
  45. import org.openxmlformats.schemas.drawingml.x2006.chart.CTPrintSettings;
  46. import org.openxmlformats.schemas.drawingml.x2006.chart.CTStrRef;
  47. import org.openxmlformats.schemas.drawingml.x2006.chart.CTTitle;
  48. import org.openxmlformats.schemas.drawingml.x2006.chart.CTTx;
  49. import org.openxmlformats.schemas.drawingml.x2006.chart.CTValAx;
  50. import org.openxmlformats.schemas.drawingml.x2006.chart.ChartSpaceDocument;
  51. import org.openxmlformats.schemas.drawingml.x2006.main.CTRegularTextRun;
  52. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextBody;
  53. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextField;
  54. import org.openxmlformats.schemas.drawingml.x2006.main.CTTextParagraph;
  55. import org.w3c.dom.Node;
  56. import org.w3c.dom.NodeList;
  57. import org.w3c.dom.Text;
  58. /**
  59. * Represents a SpreadsheetML Chart
  60. */
  61. public final class XSSFChart extends POIXMLDocumentPart implements Chart, ChartAxisFactory {
  62. /**
  63. * Parent graphic frame.
  64. */
  65. private XSSFGraphicFrame frame;
  66. /**
  67. * Root element of the SpreadsheetML Chart part
  68. */
  69. private CTChartSpace chartSpace;
  70. /**
  71. * The Chart within that
  72. */
  73. private CTChart chart;
  74. List<XSSFChartAxis> axis = new ArrayList<XSSFChartAxis>();
  75. /**
  76. * Create a new SpreadsheetML chart
  77. */
  78. protected XSSFChart() {
  79. super();
  80. createChart();
  81. }
  82. /**
  83. * Construct a SpreadsheetML chart from a package part.
  84. *
  85. * @param part the package part holding the chart data,
  86. * the content type must be <code>application/vnd.openxmlformats-officedocument.drawingml.chart+xml</code>
  87. *
  88. * @since POI 3.14-Beta1
  89. */
  90. protected XSSFChart(PackagePart part) throws IOException, XmlException {
  91. super(part);
  92. chartSpace = ChartSpaceDocument.Factory.parse(part.getInputStream(), DEFAULT_XML_OPTIONS).getChartSpace();
  93. chart = chartSpace.getChart();
  94. }
  95. /**
  96. * Construct a new CTChartSpace bean.
  97. * By default, it's just an empty placeholder for chart objects.
  98. *
  99. * @return a new CTChartSpace bean
  100. */
  101. private void createChart() {
  102. chartSpace = CTChartSpace.Factory.newInstance();
  103. chart = chartSpace.addNewChart();
  104. CTPlotArea plotArea = chart.addNewPlotArea();
  105. plotArea.addNewLayout();
  106. chart.addNewPlotVisOnly().setVal(true);
  107. CTPrintSettings printSettings = chartSpace.addNewPrintSettings();
  108. printSettings.addNewHeaderFooter();
  109. CTPageMargins pageMargins = printSettings.addNewPageMargins();
  110. pageMargins.setB(0.75);
  111. pageMargins.setL(0.70);
  112. pageMargins.setR(0.70);
  113. pageMargins.setT(0.75);
  114. pageMargins.setHeader(0.30);
  115. pageMargins.setFooter(0.30);
  116. printSettings.addNewPageSetup();
  117. }
  118. /**
  119. * Return the underlying CTChartSpace bean, the root element of the SpreadsheetML Chart part.
  120. *
  121. * @return the underlying CTChartSpace bean
  122. */
  123. @Internal
  124. public CTChartSpace getCTChartSpace(){
  125. return chartSpace;
  126. }
  127. /**
  128. * Return the underlying CTChart bean, within the Chart Space
  129. *
  130. * @return the underlying CTChart bean
  131. */
  132. @Internal
  133. public CTChart getCTChart(){
  134. return chart;
  135. }
  136. @Override
  137. protected void commit() throws IOException {
  138. XmlOptions xmlOptions = new XmlOptions(DEFAULT_XML_OPTIONS);
  139. /*
  140. Saved chart space must have the following namespaces set:
  141. <c:chartSpace
  142. xmlns:c="http://schemas.openxmlformats.org/drawingml/2006/chart"
  143. xmlns:a="http://schemas.openxmlformats.org/drawingml/2006/main"
  144. xmlns:r="http://schemas.openxmlformats.org/officeDocument/2006/relationships">
  145. */
  146. xmlOptions.setSaveSyntheticDocumentElement(new QName(CTChartSpace.type.getName().getNamespaceURI(), "chartSpace", "c"));
  147. PackagePart part = getPackagePart();
  148. OutputStream out = part.getOutputStream();
  149. chartSpace.save(out, xmlOptions);
  150. out.close();
  151. }
  152. /**
  153. * Returns the parent graphic frame.
  154. * @return the graphic frame this chart belongs to
  155. */
  156. public XSSFGraphicFrame getGraphicFrame() {
  157. return frame;
  158. }
  159. /**
  160. * Sets the parent graphic frame.
  161. */
  162. protected void setGraphicFrame(XSSFGraphicFrame frame) {
  163. this.frame = frame;
  164. }
  165. public XSSFChartDataFactory getChartDataFactory() {
  166. return XSSFChartDataFactory.getInstance();
  167. }
  168. public XSSFChart getChartAxisFactory() {
  169. return this;
  170. }
  171. public void plot(ChartData data, ChartAxis... chartAxis) {
  172. data.fillChart(this, chartAxis);
  173. }
  174. public XSSFValueAxis createValueAxis(AxisPosition pos) {
  175. long id = axis.size() + 1;
  176. XSSFValueAxis valueAxis = new XSSFValueAxis(this, id, pos);
  177. if (axis.size() == 1) {
  178. ChartAxis ax = axis.get(0);
  179. ax.crossAxis(valueAxis);
  180. valueAxis.crossAxis(ax);
  181. }
  182. axis.add(valueAxis);
  183. return valueAxis;
  184. }
  185. public XSSFCategoryAxis createCategoryAxis(AxisPosition pos) {
  186. long id = axis.size() + 1;
  187. XSSFCategoryAxis categoryAxis = new XSSFCategoryAxis(this, id, pos);
  188. if (axis.size() == 1) {
  189. ChartAxis ax = axis.get(0);
  190. ax.crossAxis(categoryAxis);
  191. categoryAxis.crossAxis(ax);
  192. }
  193. axis.add(categoryAxis);
  194. return categoryAxis;
  195. }
  196. public List<? extends XSSFChartAxis> getAxis() {
  197. if (axis.isEmpty() && hasAxis()) {
  198. parseAxis();
  199. }
  200. return axis;
  201. }
  202. public XSSFManualLayout getManualLayout() {
  203. return new XSSFManualLayout(this);
  204. }
  205. /**
  206. * @return true if only visible cells will be present on the chart,
  207. * false otherwise
  208. */
  209. public boolean isPlotOnlyVisibleCells() {
  210. return chart.getPlotVisOnly().getVal();
  211. }
  212. /**
  213. * @param plotVisOnly a flag specifying if only visible cells should be
  214. * present on the chart
  215. */
  216. public void setPlotOnlyVisibleCells(boolean plotVisOnly) {
  217. chart.getPlotVisOnly().setVal(plotVisOnly);
  218. }
  219. /**
  220. * Returns the title static text, or null if none is set.
  221. * Note that a title formula may be set instead.
  222. * @return static title text, if set
  223. * @deprecated POI 3.16, use {@link #getTitleText()} instead.
  224. */
  225. @Deprecated
  226. @Removal(version="4.0")
  227. public XSSFRichTextString getTitle() {
  228. return getTitleText();
  229. }
  230. /**
  231. * Returns the title static text, or null if none is set.
  232. * Note that a title formula may be set instead.
  233. * Empty text result is for backward compatibility, and could mean the title text is empty or there is a formula instead.
  234. * Check for a formula first, falling back on text for cleaner logic.
  235. * @return static title text if set,
  236. * null if there is no title,
  237. * empty string if the title text is empty or the title uses a formula instead
  238. */
  239. public XSSFRichTextString getTitleText() {
  240. if(! chart.isSetTitle()) {
  241. return null;
  242. }
  243. // TODO Do properly
  244. CTTitle title = chart.getTitle();
  245. StringBuffer text = new StringBuffer();
  246. XmlObject[] t = title
  247. .selectPath("declare namespace a='"+XSSFDrawing.NAMESPACE_A+"' .//a:t");
  248. for (int m = 0; m < t.length; m++) {
  249. NodeList kids = t[m].getDomNode().getChildNodes();
  250. final int count = kids.getLength();
  251. for (int n = 0; n < count; n++) {
  252. Node kid = kids.item(n);
  253. if (kid instanceof Text) {
  254. text.append(kid.getNodeValue());
  255. }
  256. }
  257. }
  258. return new XSSFRichTextString(text.toString());
  259. }
  260. /**
  261. * Sets the title text as a static string.
  262. * @param newTitle to use
  263. * @deprecated POI 3.16, use {@link #setTitleText(String)} instead.
  264. */
  265. @Deprecated
  266. @Removal(version="4.0")
  267. public void setTitle(String newTitle) {
  268. }
  269. /**
  270. * Sets the title text as a static string.
  271. * @param newTitle to use
  272. */
  273. public void setTitleText(String newTitle) {
  274. CTTitle ctTitle;
  275. if (chart.isSetTitle()) {
  276. ctTitle = chart.getTitle();
  277. } else {
  278. ctTitle = chart.addNewTitle();
  279. }
  280. CTTx tx;
  281. if (ctTitle.isSetTx()) {
  282. tx = ctTitle.getTx();
  283. } else {
  284. tx = ctTitle.addNewTx();
  285. }
  286. if (tx.isSetStrRef()) {
  287. tx.unsetStrRef();
  288. }
  289. CTTextBody rich;
  290. if (tx.isSetRich()) {
  291. rich = tx.getRich();
  292. } else {
  293. rich = tx.addNewRich();
  294. rich.addNewBodyPr(); // body properties must exist (but can be empty)
  295. }
  296. CTTextParagraph para;
  297. if (rich.sizeOfPArray() > 0) {
  298. para = rich.getPArray(0);
  299. } else {
  300. para = rich.addNewP();
  301. }
  302. if (para.sizeOfRArray() > 0) {
  303. CTRegularTextRun run = para.getRArray(0);
  304. run.setT(newTitle);
  305. } else if (para.sizeOfFldArray() > 0) {
  306. CTTextField fld = para.getFldArray(0);
  307. fld.setT(newTitle);
  308. } else {
  309. CTRegularTextRun run = para.addNewR();
  310. run.setT(newTitle);
  311. }
  312. }
  313. /**
  314. * Get the chart title formula expression if there is one
  315. * @return formula expression or null
  316. */
  317. public String getTitleFormula() {
  318. if(! chart.isSetTitle()) {
  319. return null;
  320. }
  321. CTTitle title = chart.getTitle();
  322. if (! title.isSetTx()) {
  323. return null;
  324. }
  325. CTTx tx = title.getTx();
  326. if (! tx.isSetStrRef()) {
  327. return null;
  328. }
  329. return tx.getStrRef().getF();
  330. }
  331. /**
  332. * Set the formula expression to use for the chart title
  333. * @param formula
  334. */
  335. public void setTitleFormula(String formula) {
  336. CTTitle ctTitle;
  337. if (chart.isSetTitle()) {
  338. ctTitle = chart.getTitle();
  339. } else {
  340. ctTitle = chart.addNewTitle();
  341. }
  342. CTTx tx;
  343. if (ctTitle.isSetTx()) {
  344. tx = ctTitle.getTx();
  345. } else {
  346. tx = ctTitle.addNewTx();
  347. }
  348. if (tx.isSetRich()) {
  349. tx.unsetRich();
  350. }
  351. CTStrRef strRef;
  352. if (tx.isSetStrRef()) {
  353. strRef = tx.getStrRef();
  354. } else {
  355. strRef = tx.addNewStrRef();
  356. }
  357. strRef.setF(formula);
  358. }
  359. public XSSFChartLegend getOrCreateLegend() {
  360. return new XSSFChartLegend(this);
  361. }
  362. public void deleteLegend() {
  363. if (chart.isSetLegend()) {
  364. chart.unsetLegend();
  365. }
  366. }
  367. private boolean hasAxis() {
  368. CTPlotArea ctPlotArea = chart.getPlotArea();
  369. int totalAxisCount =
  370. ctPlotArea.sizeOfValAxArray() +
  371. ctPlotArea.sizeOfCatAxArray() +
  372. ctPlotArea.sizeOfDateAxArray() +
  373. ctPlotArea.sizeOfSerAxArray();
  374. return totalAxisCount > 0;
  375. }
  376. private void parseAxis() {
  377. // TODO: add other axis types
  378. parseCategoryAxis();
  379. parseValueAxis();
  380. }
  381. private void parseCategoryAxis() {
  382. for (CTCatAx catAx : chart.getPlotArea().getCatAxArray()) {
  383. axis.add(new XSSFCategoryAxis(this, catAx));
  384. }
  385. }
  386. private void parseValueAxis() {
  387. for (CTValAx valAx : chart.getPlotArea().getValAxArray()) {
  388. axis.add(new XSSFValueAxis(this, valAx));
  389. }
  390. }
  391. }