1. 程式人生 > >Apache POI XWPF 特定位置插入表格、段落、圖片

Apache POI XWPF 特定位置插入表格、段落、圖片

特定位置插入表格、段落、圖片


  • 思路
    在word中做個標記,通常這個標記獨自佔據一個段落,例如

    標記示例


    我們想要在標記處插入一個表格,一個段落,一幅圖片,其中插入段落可以使用上話提到的文字替換方式,也可以用今天提到的方法。
    具體方法是,獲取這個段落,然後得到一個newXMLCursor,然後用這個遊標插入表格、段落、圖片。程式碼如下
  • 插入段落
public static void main(String[] args) throws IOException, InvalidFormatException {
    String filepath = "D:\\users\\IDEA\\POIUtils\\doc\\測試文件.docx";
    String destpath = "D:\\users\\IDEA\\POIUtils\\doc\\測試文件_result.docx";

    OPCPackage opcPackage = POIXMLDocument.openPackage(filepath);
    XWPFDocument xwpfDocument = new XWPFDocument(opcPackage);
    List<XWPFParagraph> xwpfParas = xwpfDocument.getParagraphs();
    int num=0;
    for(int i=0;i<xwpfParas.size();i++){
        if(num==3) break;
        XWPFParagraph xwpfParagraph = xwpfParas.get(i);
        String text=xwpfParagraph.getText();

        //插入段落
        if(text.equals("${mark_newParagraph}")){
            XmlCursor cursor = xwpfParagraph .getCTP().newCursor();
            XWPFParagraph newPara = xwpfDocument.insertNewParagraph(cursor);
            newPara.setAlignment(ParagraphAlignment.BOTH);//兩端對齊
            newPara.setIndentationFirstLine(480);//首行縮排24磅
            XWPFRun newParaRun = newPara.createRun();
            newParaRun.setText("這是新插入的段落!");
            newParaRun.setFontFamily("宋體");
            newParaRun.setFontSize(12);
            newParaRun.setBold(false);
            xwpfDocument.removeBodyElement(xwpfDocument.getPosOfParagraph(xwpfParagraph));
        }

        //插入表格
        if(text.equals("${mark_newTable}")){
            XmlCursor cursor= xwpfParagraph.getCTP().newCursor();
            XWPFTable table = xwpfDocument.insertNewTbl(cursor);

            XWPFTableRow row_0 = table.getRow(0);
            row_0.getCell(0).setText("姓名");
            row_0.addNewTableCell().setText("年齡");

            XWPFTableRow row_1 = table.createRow();
            row_1.getCell(0).setText("隔壁老王");
            row_1.getCell(1).setText("48");

            setTableLocation(table,"center");
            setCellLocation(table,"CENTER","center");
            xwpfDocument.removeBodyElement(xwpfDocument.getPosOfParagraph(xwpfParagraph));
        }

        //插入圖片
        if(text.equals("${mark_newPicture}")){

            XmlCursor cursor = xwpfParagraph .getCTP().newCursor();
            XWPFParagraph newPara = xwpfDocument.insertNewParagraph(cursor);
            newPara.setAlignment(ParagraphAlignment.CENTER);//居中
            XWPFRun newParaRun = newPara.createRun();
            newParaRun.addPicture(new FileInputStream("./doc/bus.png"),XWPFDocument.PICTURE_TYPE_PNG,"bus.png,",Units.toEMU(200), Units.toEMU(200));
            xwpfDocument.removeBodyElement(xwpfDocument.getPosOfParagraph(xwpfParagraph));
        }
    }

    write(xwpfDocument,destpath);
}


    /**
     * 設定單元格水平位置和垂直位置
     *
     * @param xwpfTable
     * @param verticalLoction    單元格中內容垂直上TOP,下BOTTOM,居中CENTER,BOTH兩端對齊
     * @param horizontalLocation 單元格中內容水平居中center,left居左,right居右,both兩端對齊
     */
    public static void setCellLocation(XWPFTable xwpfTable, String verticalLoction, String horizontalLocation) {
        List<XWPFTableRow> rows = xwpfTable.getRows();
        for (XWPFTableRow row : rows) {
            List<XWPFTableCell> cells = row.getTableCells();
            for (XWPFTableCell cell : cells) {
                CTTc cttc = cell.getCTTc();
                CTP ctp = cttc.getPList().get(0);
                CTPPr ctppr = ctp.getPPr();
                if (ctppr == null) {
                    ctppr = ctp.addNewPPr();
                }
                CTJc ctjc = ctppr.getJc();
                if (ctjc == null) {
                    ctjc = ctppr.addNewJc();
                }
                ctjc.setVal(STJc.Enum.forString(horizontalLocation)); //水平居中
                cell.setVerticalAlignment(XWPFTableCell.XWPFVertAlign.valueOf(verticalLoction));//垂直居中
            }
        }
    }

    /**
     * 設定表格位置
     *
     * @param xwpfTable
     * @param location  整個表格居中center,left居左,right居右,both兩端對齊
     */
    public static void setTableLocation(XWPFTable xwpfTable, String location) {
        CTTbl cttbl = xwpfTable.getCTTbl();
        CTTblPr tblpr = cttbl.getTblPr() == null ? cttbl.addNewTblPr() : cttbl.getTblPr();
        CTJc cTJc = tblpr.addNewJc();
        cTJc.setVal(STJc.Enum.forString(location));
    }
  • 實驗結果

     



作者:Pantheon
連結:https://www.jianshu.com/p/de58ab550157
來源:簡書
簡書著作權歸作者所有,任何形式的轉載都請聯絡作者獲得授權並註明出處。