Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- import java.awt.geom.Rectangle2D;
- import java.io.FileInputStream;
- import java.io.FileOutputStream;
- import java.io.IOException;
- import java.util.Iterator;
- import java.util.List;
- import org.apache.poi.xslf.usermodel.XMLSlideShow;
- import org.apache.poi.xslf.usermodel.XSLFSlide;
- import org.apache.poi.xslf.usermodel.XSLFTable;
- import org.apache.poi.xslf.usermodel.XSLFTableCell;
- import org.apache.poi.xslf.usermodel.XSLFTableRow;
- import org.openxmlformats.schemas.drawingml.x2006.main.CTTableCell;
- public class XslfRemoveTableColumn {
- public static void main(String args[]) throws IOException {
- // prepare sample table/slide with merged cells
- XMLSlideShow ppt = new XMLSlideShow();
- XSLFSlide sl = ppt.createSlide();
- XSLFTable tab = sl.createTable();
- initRow(tab, "111111");
- initRow(tab, "122122");
- initRow(tab, "112222");
- initRow(tab, "133322");
- initRow(tab, "333122");
- tab.setAnchor(new Rectangle2D.Double(100, 100, 200, 200));
- try (FileOutputStream fos = new FileOutputStream("bla.pptx")) {
- ppt.write(fos);
- }
- ppt.close();
- try (FileInputStream fis = new FileInputStream("bla.pptx")) {
- ppt = new XMLSlideShow(fis);
- }
- tab = (XSLFTable)ppt.getSlides().get(0).getShapes().get(0);
- // actually remove the column
- removeColumn(tab, 3);
- try (FileOutputStream fos = new FileOutputStream("bla2.pptx")) {
- ppt.write(fos);
- }
- ppt.close();
- }
- private static void removeColumn(XSLFTable table, int col) {
- nextRow:for (final XSLFTableRow row : table) {
- Iterator<XSLFTableCell> it = row.iterator();
- int gridSpan;
- for (int idx=0, idxXml=0; it.hasNext(); idx+=gridSpan, idxXml++) {
- final XSLFTableCell c = it.next();
- gridSpan = c.getGridSpan();
- if (idx <= col && col < idx+gridSpan) {
- if (gridSpan > 1) {
- ((CTTableCell)c.getXmlObject()).setGridSpan(gridSpan-1);
- // check for merged cells
- for (; it.hasNext() && idx<col; idx++, idxXml++) {
- final XSLFTableCell mergedC = it.next();
- if (!mergedC.isMerged()) {
- continue nextRow;
- }
- }
- }
- row.getXmlObject().removeTc(idxXml);
- it.remove();
- break;
- }
- }
- }
- table.getCTTable().getTblGrid().removeGridCol(col);
- }
- private static List<XSLFTableCell> initRow(XSLFTable table, String iv) {
- XSLFTableRow row = table.addRow();
- for (int idx=0; idx<iv.length(); idx++) {
- XSLFTableCell c = row.addCell();
- c.setText(""+idx);
- int span = iv.charAt(idx)-'0';
- if (span > 1) {
- ((CTTableCell)c.getXmlObject()).setGridSpan(span);
- }
- for (int spanIdx=0; spanIdx<span-1; spanIdx++, idx++) {
- c = row.addCell();
- ((CTTableCell)c.getXmlObject()).setHMerge(true);
- }
- }
- return row.getCells();
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement