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.

XSLFTable.java 15KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443
  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.xslf.usermodel;
  20. import java.awt.geom.Rectangle2D;
  21. import java.util.ArrayList;
  22. import java.util.Collections;
  23. import java.util.Iterator;
  24. import java.util.List;
  25. import javax.xml.namespace.QName;
  26. import org.apache.poi.sl.draw.DrawFactory;
  27. import org.apache.poi.sl.draw.DrawTableShape;
  28. import org.apache.poi.sl.draw.DrawTextShape;
  29. import org.apache.poi.sl.usermodel.TableShape;
  30. import org.apache.poi.util.Internal;
  31. import org.apache.poi.util.Units;
  32. import org.apache.poi.xddf.usermodel.text.XDDFTextBody;
  33. import org.apache.xmlbeans.XmlCursor;
  34. import org.apache.xmlbeans.XmlObject;
  35. import org.apache.xmlbeans.impl.values.XmlAnyTypeImpl;
  36. import org.openxmlformats.schemas.drawingml.x2006.main.CTGraphicalObjectData;
  37. import org.openxmlformats.schemas.drawingml.x2006.main.CTNonVisualDrawingProps;
  38. import org.openxmlformats.schemas.drawingml.x2006.main.CTTable;
  39. import org.openxmlformats.schemas.drawingml.x2006.main.CTTableCol;
  40. import org.openxmlformats.schemas.drawingml.x2006.main.CTTableRow;
  41. import org.openxmlformats.schemas.presentationml.x2006.main.CTGraphicalObjectFrame;
  42. import org.openxmlformats.schemas.presentationml.x2006.main.CTGraphicalObjectFrameNonVisual;
  43. /**
  44. * Represents a table in a .pptx presentation
  45. */
  46. public class XSLFTable extends XSLFGraphicFrame implements Iterable<XSLFTableRow>,
  47. TableShape<XSLFShape,XSLFTextParagraph> {
  48. /* package */ static final String TABLE_URI = "http://schemas.openxmlformats.org/drawingml/2006/table";
  49. private CTTable _table;
  50. private List<XSLFTableRow> _rows;
  51. /*package*/ XSLFTable(CTGraphicalObjectFrame shape, XSLFSheet sheet){
  52. super(shape, sheet);
  53. CTGraphicalObjectData god = shape.getGraphic().getGraphicData();
  54. XmlCursor xc = god.newCursor();
  55. try {
  56. if (!xc.toChild(XSLFRelation.NS_DRAWINGML, "tbl")) {
  57. throw new IllegalStateException("a:tbl element was not found in\n " + god);
  58. }
  59. XmlObject xo = xc.getObject();
  60. // Pesky XmlBeans bug - see Bugzilla #49934
  61. // it never happens when using the full ooxml-schemas jar but may happen with the abridged poi-ooxml-schemas
  62. if (xo instanceof XmlAnyTypeImpl){
  63. String errStr =
  64. "Schemas (*.xsb) for CTTable can't be loaded - usually this happens when OSGI " +
  65. "loading is used and the thread context classloader has no reference to " +
  66. "the xmlbeans classes"
  67. ;
  68. throw new IllegalStateException(errStr);
  69. }
  70. _table = (CTTable)xo;
  71. } finally {
  72. xc.dispose();
  73. }
  74. _rows = new ArrayList<>(_table.sizeOfTrArray());
  75. for(CTTableRow row : _table.getTrList()) {
  76. _rows.add(new XSLFTableRow(row, this));
  77. }
  78. updateRowColIndexes();
  79. }
  80. @Override
  81. public XSLFTableCell getCell(int row, int col) {
  82. if (row < 0 || _rows.size() <= row) {
  83. return null;
  84. }
  85. XSLFTableRow r = _rows.get(row);
  86. if (r == null) {
  87. // empty row
  88. return null;
  89. }
  90. List<XSLFTableCell> cells = r.getCells();
  91. if (col < 0 || cells.size() <= col) {
  92. return null;
  93. }
  94. // cell can be potentially empty ...
  95. return cells.get(col);
  96. }
  97. @Internal
  98. public CTTable getCTTable(){
  99. return _table;
  100. }
  101. @Override
  102. public int getNumberOfColumns() {
  103. return _table.getTblGrid().sizeOfGridColArray();
  104. }
  105. @Override
  106. public int getNumberOfRows() {
  107. return _table.sizeOfTrArray();
  108. }
  109. @Override
  110. public double getColumnWidth(int idx){
  111. return Units.toPoints(
  112. _table.getTblGrid().getGridColArray(idx).getW());
  113. }
  114. @Override
  115. public void setColumnWidth(int idx, double width) {
  116. _table.getTblGrid().getGridColArray(idx).setW(Units.toEMU(width));
  117. }
  118. @Override
  119. public double getRowHeight(int row) {
  120. return Units.toPoints(_table.getTrArray(row).getH());
  121. }
  122. @Override
  123. public void setRowHeight(int row, double height) {
  124. _table.getTrArray(row).setH(Units.toEMU(height));
  125. }
  126. @Override
  127. public Iterator<XSLFTableRow> iterator(){
  128. return _rows.iterator();
  129. }
  130. public List<XSLFTableRow> getRows(){
  131. return Collections.unmodifiableList(_rows);
  132. }
  133. public XSLFTableRow addRow(){
  134. CTTableRow tr = _table.addNewTr();
  135. XSLFTableRow row = initializeRow(tr);
  136. _rows.add(row);
  137. return row;
  138. }
  139. private XSLFTableRow initializeRow(CTTableRow tr) {
  140. XSLFTableRow row = new XSLFTableRow(tr, this);
  141. // default height is 20 points
  142. row.setHeight(20.0);
  143. for (int i = 0; i < getNumberOfColumns(); i++) {
  144. row.addCell();
  145. }
  146. return row;
  147. }
  148. /**
  149. * Insert a new row at the given index.
  150. * @param rowIdx the row index.
  151. * @since POI 5.0.0
  152. */
  153. public XSLFTableRow insertRow(int rowIdx) {
  154. if (getNumberOfRows() < rowIdx) {
  155. throw new IndexOutOfBoundsException("Cannot insert row at " + rowIdx + "; table has only " + getNumberOfRows() + "rows.");
  156. }
  157. CTTableRow tr = _table.insertNewTr(rowIdx);
  158. XSLFTableRow row = initializeRow(tr);
  159. _rows.add(rowIdx, row);
  160. return row;
  161. }
  162. /**
  163. * Remove the row on the given index
  164. * @param rowIdx the row index
  165. */
  166. public void removeRow(int rowIdx) {
  167. if (getNumberOfRows() < rowIdx) {
  168. throw new IndexOutOfBoundsException("Cannot remove row at " + rowIdx + "; table has only " + getNumberOfRows() + "rows.");
  169. }
  170. _table.removeTr(rowIdx);
  171. _rows.remove(rowIdx);
  172. updateRowColIndexes();
  173. }
  174. /**
  175. * Add a new column at the end of the table.
  176. * @since POI 4.1.2
  177. */
  178. public void addColumn() {
  179. long width = _table.getTblGrid().getGridColArray(getNumberOfColumns() - 1).getW();
  180. CTTableCol col = _table.getTblGrid().addNewGridCol();
  181. col.setW(width);
  182. for (XSLFTableRow row : _rows) {
  183. XSLFTableCell cell = row.addCell();
  184. new XDDFTextBody(cell, cell.getTextBody(true)).initialize();
  185. }
  186. }
  187. /**
  188. * Insert a new column at the given index.
  189. * @param colIdx the column index.
  190. * @since POI 4.1.2
  191. */
  192. public void insertColumn(int colIdx) {
  193. if (getNumberOfColumns() < colIdx) {
  194. throw new IndexOutOfBoundsException("Cannot insert column at " + colIdx + "; table has only " + getNumberOfColumns() + "columns.");
  195. }
  196. long width = _table.getTblGrid().getGridColArray(colIdx).getW();
  197. CTTableCol col = _table.getTblGrid().insertNewGridCol(colIdx);
  198. col.setW(width);
  199. for (XSLFTableRow row : _rows) {
  200. XSLFTableCell cell = row.insertCell(colIdx);
  201. new XDDFTextBody(cell, cell.getTextBody(true)).initialize();
  202. }
  203. }
  204. /**
  205. * Remove the column at the given index.
  206. * @param colIdx the column index.
  207. * @since POI 4.1.2
  208. */
  209. public void removeColumn(int colIdx) {
  210. if (getNumberOfColumns() < colIdx) {
  211. throw new IndexOutOfBoundsException("Cannot remove column at " + colIdx + "; table has only " + getNumberOfColumns() + "columns.");
  212. }
  213. _table.getTblGrid().removeGridCol(colIdx);
  214. for (XSLFTableRow row : _rows) {
  215. row.removeCell(colIdx);
  216. }
  217. }
  218. static CTGraphicalObjectFrame prototype(int shapeId){
  219. CTGraphicalObjectFrame frame = CTGraphicalObjectFrame.Factory.newInstance();
  220. CTGraphicalObjectFrameNonVisual nvGr = frame.addNewNvGraphicFramePr();
  221. CTNonVisualDrawingProps cnv = nvGr.addNewCNvPr();
  222. cnv.setName("Table " + shapeId);
  223. cnv.setId(shapeId);
  224. nvGr.addNewCNvGraphicFramePr().addNewGraphicFrameLocks().setNoGrp(true);
  225. nvGr.addNewNvPr();
  226. frame.addNewXfrm();
  227. CTGraphicalObjectData gr = frame.addNewGraphic().addNewGraphicData();
  228. XmlCursor grCur = gr.newCursor();
  229. grCur.toNextToken();
  230. grCur.beginElement(new QName(XSLFRelation.NS_DRAWINGML, "tbl"));
  231. CTTable tbl = CTTable.Factory.newInstance();
  232. tbl.addNewTblPr();
  233. tbl.addNewTblGrid();
  234. XmlCursor tblCur = tbl.newCursor();
  235. tblCur.moveXmlContents(grCur);
  236. tblCur.dispose();
  237. grCur.dispose();
  238. gr.setUri(TABLE_URI);
  239. return frame;
  240. }
  241. /**
  242. * Merge cells of a table
  243. */
  244. @SuppressWarnings("unused")
  245. public void mergeCells(int firstRow, int lastRow, int firstCol, int lastCol) {
  246. if(firstRow > lastRow) {
  247. throw new IllegalArgumentException(
  248. "Cannot merge, first row > last row : "
  249. + firstRow + " > " + lastRow
  250. );
  251. }
  252. if(firstCol > lastCol) {
  253. throw new IllegalArgumentException(
  254. "Cannot merge, first column > last column : "
  255. + firstCol + " > " + lastCol
  256. );
  257. }
  258. int rowSpan = (lastRow - firstRow) + 1;
  259. boolean mergeRowRequired = rowSpan > 1;
  260. int colSpan = (lastCol - firstCol) + 1;
  261. boolean mergeColumnRequired = colSpan > 1;
  262. for(int i = firstRow; i <= lastRow; i++) {
  263. XSLFTableRow row = _rows.get(i);
  264. for(int colPos = firstCol; colPos <= lastCol; colPos++) {
  265. XSLFTableCell cell = row.getCells().get(colPos);
  266. if(mergeRowRequired) {
  267. if(i == firstRow) {
  268. cell.setRowSpan(rowSpan);
  269. } else {
  270. cell.setVMerge();
  271. }
  272. }
  273. if(mergeColumnRequired) {
  274. if(colPos == firstCol) {
  275. cell.setGridSpan(colSpan);
  276. } else {
  277. cell.setHMerge();
  278. }
  279. }
  280. }
  281. }
  282. }
  283. /**
  284. * Get assigned TableStyle
  285. *
  286. * @return the assigned TableStyle
  287. *
  288. * @since POI 3.15-beta2
  289. */
  290. protected XSLFTableStyle getTableStyle() {
  291. CTTable tab = getCTTable();
  292. // TODO: support inline table style
  293. if (!tab.isSetTblPr() || !tab.getTblPr().isSetTableStyleId()) {
  294. return null;
  295. }
  296. String styleId = tab.getTblPr().getTableStyleId();
  297. XSLFTableStyles styles = getSheet().getSlideShow().getTableStyles();
  298. for (XSLFTableStyle style : styles.getStyles()) {
  299. if (style.getStyleId().equals(styleId)) {
  300. return style;
  301. }
  302. }
  303. return null;
  304. }
  305. /* package */ void updateRowColIndexes() {
  306. int rowIdx = 0;
  307. for (XSLFTableRow xr : this) {
  308. int colIdx = 0;
  309. for (XSLFTableCell tc : xr) {
  310. tc.setRowColIndex(rowIdx, colIdx);
  311. colIdx++;
  312. }
  313. rowIdx++;
  314. }
  315. }
  316. /**
  317. * Calculates the bounding boxes of all cells and updates the dimension of the table
  318. */
  319. public void updateCellAnchor() {
  320. int rows = getNumberOfRows();
  321. int cols = getNumberOfColumns();
  322. double[] colWidths = new double[cols];
  323. double[] rowHeights = new double[rows];
  324. for (int row=0; row<rows; row++) {
  325. rowHeights[row] = getRowHeight(row);
  326. }
  327. for (int col=0; col<cols; col++) {
  328. colWidths[col] = getColumnWidth(col);
  329. }
  330. Rectangle2D tblAnc = getAnchor();
  331. DrawFactory df = DrawFactory.getInstance(null);
  332. double nextY = tblAnc.getY();
  333. double nextX = tblAnc.getX();
  334. // #1 pass - determine row heights, the height values might be too low or 0 ...
  335. for (int row=0; row<rows; row++) {
  336. double maxHeight = 0;
  337. for (int col=0; col<cols; col++) {
  338. XSLFTableCell tc = getCell(row, col);
  339. if (tc == null || tc.getGridSpan() != 1 || tc.getRowSpan() != 1) {
  340. continue;
  341. }
  342. // need to set the anchor before height calculation
  343. tc.setAnchor(new Rectangle2D.Double(0,0,colWidths[col],0));
  344. DrawTextShape dts = df.getDrawable(tc);
  345. maxHeight = Math.max(maxHeight, dts.getTextHeight());
  346. }
  347. rowHeights[row] = Math.max(rowHeights[row],maxHeight);
  348. }
  349. // #2 pass - init properties
  350. for (int row=0; row<rows; row++) {
  351. nextX = tblAnc.getX();
  352. for (int col=0; col<cols; col++) {
  353. Rectangle2D bounds = new Rectangle2D.Double(nextX, nextY, colWidths[col], rowHeights[row]);
  354. XSLFTableCell tc = getCell(row, col);
  355. if (tc != null) {
  356. tc.setAnchor(bounds);
  357. nextX += colWidths[col]+DrawTableShape.borderSize;
  358. }
  359. }
  360. nextY += rowHeights[row]+DrawTableShape.borderSize;
  361. }
  362. // #3 pass - update merge info
  363. for (int row=0; row<rows; row++) {
  364. for (int col=0; col<cols; col++) {
  365. XSLFTableCell tc = getCell(row, col);
  366. if (tc == null) {
  367. continue;
  368. }
  369. Rectangle2D mergedBounds = tc.getAnchor();
  370. for (int col2=col+1; col2<col+tc.getGridSpan(); col2++) {
  371. assert(col2 < cols);
  372. XSLFTableCell tc2 = getCell(row, col2);
  373. assert(tc2.getGridSpan() == 1 && tc2.getRowSpan() == 1);
  374. mergedBounds.add(tc2.getAnchor());
  375. }
  376. for (int row2=row+1; row2<row+tc.getRowSpan(); row2++) {
  377. assert(row2 < rows);
  378. XSLFTableCell tc2 = getCell(row2, col);
  379. assert(tc2.getGridSpan() == 1 && tc2.getRowSpan() == 1);
  380. mergedBounds.add(tc2.getAnchor());
  381. }
  382. tc.setAnchor(mergedBounds);
  383. }
  384. }
  385. setAnchor(new Rectangle2D.Double(tblAnc.getX(),tblAnc.getY(),
  386. nextX-tblAnc.getX(),
  387. nextY-tblAnc.getY()));
  388. }
  389. }