Loading

POI 扩展方法

POI 扩展方法

  • 指定位置插入表:
  public static XWPFTable insertNewTable(XWPFDocument doc, int pos, int row, int col){
      List<IBodyElement> bodyElements = doc.getBodyElements();
      XmlCursor cursor = getCursor(bodyElements.get(pos));
      String uri = CTTbl.type.getName().getNamespaceURI();
      String localPart = "tbl";
      cursor.beginElement(localPart, uri);
      cursor.toParent();
      CTTbl t = (CTTbl)cursor.getObject();
      XWPFTable table = new XWPFTable(t, doc,  row, col);
}
  • 表格设置固定宽度,设置列宽比例
  public static void setColumnWidth(XWPFTable table, int tableWidth, boolean fixedWidth, double[] colWidthRadio) {
      CTTblWidth ctTblWidth = CTTblWidth.Factory.newInstance();
      ctTblWidth.setType(STTblWidth.DXA);
      if (fixedWidth) {
          if (colWidthRadio != null && colWidthRadio.length > 0) {
              CTTblPr tblPr = table.getCTTbl().addNewTblPr();
              tblPr.setTblLayout(CTTblLayoutType.Factory.newInstance());
              tblPr.getTblLayout().setType(STTblLayoutType.FIXED);
              tblPr.setTblW(ctTblWidth);
              tblPr.getTblW().setW(BigInteger.valueOf(tableWidth));
              if(table.getCTTbl().getTblGrid() == null)
                  table.getCTTbl().addNewTblGrid();
              for (int i = 0; i < colWidthRadio.length; i++) {
                  table.getCTTbl().getTblGrid().addNewGridCol().setW(tableWidth * colWidthRadio[i]);
              }
              return;
          } else {
              throw new UnsupportedOperationException("暂未实现");
          }
      }
  }
  • 合并单元格:
  public static void mergeCells(XWPFTableRow row, int startIndex, int endIndex) {
      XWPFTableCell cell = row.getCell(startIndex);
      for(int i = endIndex; i > startIndex; i--) {
          row.removeCell(i);
      }
      if(!cell.getCTTc().isSetTcPr())
      {
          cell.getCTTc().addNewTcPr();
      }

      CTTcPr tcpr = cell.getCTTc().getTcPr();
      if(tcpr.getGridSpan() == null)
          tcpr.addNewGridSpan();

      CTDecimalNumber gridSpan = tcpr.getGridSpan();
      gridSpan.setVal(BigInteger.valueOf(endIndex-startIndex+1));
}
  • 指定位置插入段落:
  public static XWPFParagraph insertNewParagraph(XWPFDocument doc, int pos)
  {
      XmlCursor cursor = getCursor(doc.getBodyElements().get(pos));
      XWPFParagraph newPara = doc.insertNewParagraph(cursor);
      return  newPara;
  }
posted @ 2025-03-20 11:36  一起滚月球  阅读(75)  评论(0)    收藏  举报