使用Word模板通過(guò)替換變量的方法實(shí)現(xiàn)word導(dǎo)出

介紹一個(gè)使用word模板生成word的方法,同樣是通過(guò)替換模板中的變量來(lái)達(dá)成目的,使用POI。
Word模板如下:


word模板

具體實(shí)現(xiàn)步驟如下:

  1. 創(chuàng)建XwpfTUtil工具類,詳細(xì)代碼見(jiàn)文末。
  2. 在實(shí)現(xiàn)方法中創(chuàng)建XwpfTUtil實(shí)例
XwpfTUtil xwpfUtil = new XwpfTUtil();
  1. 創(chuàng)建輸入流和XWPFDocument實(shí)例
InputStream is = new FileInputStream(“Word模板路徑”);
XWPFDocument doc = new XWPFDocument(is);
  1. 替換模板中的變量,doc為XWPFDocument實(shí)例,map里存放著要替換的值
 xwpfTUtil.replaceInPara(doc, map);
 xwpfTUtil.replaceInTable(doc, map);
  1. 創(chuàng)建輸出流并生成Word,關(guān)閉各個(gè)流
OutputStream os =response.outputStream;(web應(yīng)用中可以這樣)
doc.write(os);
xwpfTUtil.close(os)
xwpfTUtil.close(is);
os.flush();
os.close();

至此,Word就生成了。
XwpfTUtil的源碼見(jiàn)下:

public class XwpfTUtil {

    /**
     * 替換段落里面的變量
     * @param doc    要替換的文檔
     * @param params 參數(shù)
     */
    public voidreplaceInPara(XWPFDocument doc, Map<String, Object> params) {
        Iterator<XWPFParagraph> iterator = doc.getParagraphsIterator();
        XWPFParagraph para;
        while(iterator.hasNext()) {
            para =iterator.next();
            this.replaceInPara(para, params);
        }
    }

    /**
     * 替換段落里面的變量
     * @param para   要替換的段落
     * @param params 參數(shù)
     */
    public voidreplaceInPara(XWPFParagraph para, Map<String, Object> params) {
        List<XWPFRun>runs;
        Matcher matcher;
        if (this.matcher(para.getParagraphText()).find()){
            runs =para.getRuns();
            int start = -1;
            int end = -1;
            String str ="";
            for (int i = 0; i< runs.size(); i++) {
                XWPFRun run =runs.get(i);
                String runText = run.toString();
                if ('$' ==runText.charAt(0)&&'{' == runText.charAt(1)) {
                    start = i;
                }
                if ((start !=-1)) {
                    str +=runText;
                }
                if ('}' ==runText.charAt(runText.length() - 1)) {
                    if (start!= -1) {
                        end =i;
                        break;
                    }
                }
            }
            for (int i =start; i <= end; i++) {
                para.removeRun(i);
                i--;
                end--;
            }
            for (String key :params.keySet()) {
                if (str.equals(key)){
                    para.createRun().setText((String) params.get(key));
                    break;
                }
            }
        }
    }

    /**
     * 替換表格里面的變量
     * @param doc    要替換的文檔
     * @param params 參數(shù)
     */
    public voidreplaceInTable(XWPFDocument doc, Map<String, Object> params) {
        Iterator<XWPFTable> iterator = doc.getTablesIterator();
        XWPFTable table;
        List<XWPFTableRow> rows;
        List<XWPFTableCell> cells;
        List<XWPFParagraph>paras;
        while(iterator.hasNext()) {
            table =iterator.next();
            rows =table.getRows();
            for (XWPFTableRowrow : rows) {
                cells =row.getTableCells();
                for(XWPFTableCell cell : cells) {
                    paras =cell.getParagraphs();
                    for(XWPFParagraph para : paras) {
                       this.replaceInPara(para, params);
                    }
                }
            }
        }
    }

    /**
     * 正則匹配字符串
     * @param str
     * @return
     */
    private Matchermatcher(String str) {
        Pattern pattern =Pattern.compile("\\$\\{(.+?)\\}", Pattern.CASE_INSENSITIVE);
        Matcher matcher =pattern.matcher(str);
        return matcher;
    }

    /**
     * 關(guān)閉輸入流
     * @param is
     */
    public voidclose(InputStream is) {
        if (is != null) {
            try {
                is.close();
            } catch(IOException e) {
               e.printStackTrace();
            }
        }
    }

    /**
     * 關(guān)閉輸出流
     * @param os
     */
    public voidclose(OutputStream os) {
        if (os != null) {
            try {
                os.close();
            } catch(IOException e) {
                e.printStackTrace();
            }
        }

    }

}
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請(qǐng)聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時(shí)請(qǐng)結(jié)合常識(shí)與多方信息審慎甄別。
平臺(tái)聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點(diǎn),簡(jiǎn)書系信息發(fā)布平臺(tái),僅提供信息存儲(chǔ)服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容