docx文件转freemaker 工具方法

1.新建 word文件,调整好格式

如图:

另存为xml文件

 

修改扩展名字为ftl就可以了,

把模版数据填充到模版中:

public static String jsonToword(JSONObject jsonObject) {
    String wordPath = null;
    try {
        JSONObject agreement = jsonObject.getJSONObject("agreement");
        String tempFileName = "tpl_protocol_book";
        JSONArray lossList = agreement.getJSONArray("lossList");
        StringBuffer sb = new StringBuffer();
        for (int i = 0; i < lossList.size(); i++) {
            if (i == lossList.size() - 1) {
                sb.append(lossList.getJSONObject(i).getStr("personName"));
            } else {
                sb.append(lossList.getJSONObject(i).getStr("personName") + "、");
            }
        }
        //这里的文件名用uuid,因为暂存的时候可能没有录入客户姓名
        String fileName = UuidUtils.getUUID() + ".docx";
        Map<String, Object> dataMap = new HashMap<>();
        dataMap.put("damageDate", agreement.getStr("damageDate"));
        dataMap.put("licenseNo", agreement.getStr("licenseNo"));
        dataMap.put("damageAddress", agreement.getStr("damageAddress"));
        dataMap.put("earlyPayAmount", agreement.getStr("earlyPayAmount"));
        dataMap.put("sumIndemnity", agreement.getStr("sumIndemnity"));
        dataMap.put("insuredDuty", agreement.getStr("insuredDuty"));
        dataMap.put("payInfoList", agreement.getJSONArray("payInfoList"));
        dataMap.put("lossList", lossList);
        dataMap.put("remark", agreement.getStr("remark"));
        dataMap.put("insuredName", agreement.getStr("insuredName"));
        dataMap.put("insuredCertiCode", agreement.getStr("insuredCertiCode"));
        dataMap.put("beInsureSignList", jsonObject.containsKey("beInsureSignList") ? jsonObject.getJSONArray("beInsureSignList") : new JSONArray());
        dataMap.put("hurtSignList", jsonObject.containsKey("hurtSignList") ? jsonObject.getJSONArray("hurtSignList") : new JSONArray());
        String dir = Thread.currentThread().getContextClassLoader().getResource("").getPath() + "tpl_document" + File.separator + "temp" + File.separator;
        FreeMarkerUtil.outDocumentFile(dir.substring(1) + fileName, fileName, tempFileName, dataMap);
        wordPath = dir.substring(1) + fileName;
    } catch (Exception e) {
        e.printStackTrace();
    }
    return wordPath;
}
 
@Slf4j
@Component
public class FreeMarkerUtil {

    private static Configuration config;

    /**
     * @param tempFilePath  临时文件路径
     * @param finalFilePath 最终文件路径
     * @param tempFileName  模版文件路径
     * @param dataMap 模版数据
     * @return
     */
    public static boolean outDocumentFile(String tempFilePath, String finalFilePath, String tempFileName, Map<String, Object> dataMap) {
        try {
            /** 初始化模版配置文件 **/
            config = new Configuration();
            /** 设置编码 **/
            config.setDefaultEncoding("utf-8");
            String fileDirectory = null;
            fileDirectory = ResourceUtils.getFile("classpath:tpl_document").getAbsolutePath();
            /** 加载文件 **/
            config.setDirectoryForTemplateLoading(new File(fileDirectory));
            String docxTemplate = ResourceUtils.getFile("classpath:tpl_document" + File.separator + tempFileName + ".docx").getAbsolutePath();
            /** 加载模板 **/
            Template template = config.getTemplate(tempFileName + ".ftl");
            /** 指定输出word文件的路径 **/
            FileOutputStream fos = new FileOutputStream(new File(tempFilePath));
            Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"), 10240);
            template.process(dataMap, out);
            if (out != null) {
                out.close();
            }
            outDocx(new File(tempFilePath), docxTemplate, finalFilePath);
        } catch (Exception e) {
            log.error("outDocumentFile 生成文档失败!, 使用的模板名是: {}", tempFileName, e);
            return false;
        }
        log.info("outDocumentFile 生成文档成功!, 使用的模板名是: {}", tempFileName);
        return true;
    }

    /**
     * 转为doc
     *
     * @param documentFile 动态生成数据的docunment.xml文件
     * @param docxTemplate docx的模板
     * @param toFilePath   需要导出的文件路径
     */
    public static void outDocx(File documentFile, String docxTemplate, String toFilePath) throws ZipException, IOException {
        try {
            File docxFile = new File(docxTemplate);
            ZipFile zipFile = new ZipFile(docxFile);
            Enumeration<? extends ZipEntry> zipEntrys = zipFile.entries();
            ZipOutputStream zipout = new ZipOutputStream(new FileOutputStream(toFilePath));
            int len = -1;
            byte[] buffer = new byte[1024];
            while (zipEntrys.hasMoreElements()) {
                ZipEntry next = zipEntrys.nextElement();
                InputStream is = zipFile.getInputStream(next);
                // 把输入流的文件传到输出流中 如果是word/document.xml由我们输入
                zipout.putNextEntry(new ZipEntry(next.toString()));
                if ("word/document.xml".equals(next.toString())) {
                    InputStream in = new FileInputStream(documentFile);
                    while ((len = in.read(buffer)) != -1) {
                        zipout.write(buffer, 0, len);
                    }
                    in.close();
                } else {
                    while ((len = is.read(buffer)) != -1) {
                        zipout.write(buffer, 0, len);
                    }
                    is.close();
                }
            }
            zipout.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }


}

 

 

 

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

焱童鞋

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值