使用java poi 替換word模板裏面的內容

需求背景

業務提供了一個word的簽名模板,要求根據訂單內容替換模板中的關鍵信息,需要替換的內容已明確。
在這裏插入圖片描述

功能實現

對模板進一步加工,方便我們程序處理

第一步,我們需要做的就是對模板進行進一步加工處理,將替換的內容使用固定的標籤標誌。如下圖所示
在這裏插入圖片描述
(使用${}來聲明關鍵詞的原因是爲了方便查看和防止原文中有相同的單詞,類似freemark的標籤,非必須的,可根據自己需要加工即可)。

java代碼

 @Override
    public File generateAttorneySignatureFile(Map<String, String> dataMap) throws IOException {
        File exportFile = new File("D:\\tmp\\written+form-模板標記1.doc");
        InputStream ins = new FileInputStream(new File("D:\\tmp\\written+form-模板標記.doc"));
        HWPFDocument document = new HWPFDocument(ins);
        // 讀取word的文本內容
        Range bodyRange = document.getRange();
        // 根據第二部加工的key進行替換
        for (Map.Entry<String, String> entry : dataMap.entrySet()) {
            bodyRange.replaceText("${" + entry.getKey() + "}", entry.getValue());
        }
        //寫入新文件
        try {
            ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
            document.write(byteArrayOutputStream);
            OutputStream outputStream = new FileOutputStream(exportFile);
            outputStream.write(byteArrayOutputStream.toByteArray());
            outputStream.close();
        } catch (IOException e) {
            Logs.error(e.getMessage(), e);
        }
        return exportFile;
    }

驗證

執行以下代碼,進行驗證,得到的新的簽名文檔內容如圖所示:

  Map<String, String> map = new HashMap<>();
        map.put("markName", "HE OR SHE");
        map.put("markType", "markType");
        map.put("applyName", "FeianlING");
        wordExportService.generateAttorneySignatureFile(map);

在這裏插入圖片描述
done

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章