Java FreeMarker 编辑导出 word 文档

首先需要一个word文件作为模板,例如
在这里插入图片描述
${name} 是将要替换的变量。 在需要的地方,放上变量会自动替换。如果定义了变量却没有值来替换,会报错

导入依赖

        <dependency>
            <groupId>org.freemarker</groupId>
            <artifactId>freemarker</artifactId>
            <version>2.3.28</version>
        </dependency>

关键代码

@Override
    public Map<String,Object> getDimensionAreaData(ParameterVO parameterVO) {

        try {
           
                Configuration configuration = new Configuration(new Version("2.3.0"));
                configuration.setDefaultEncoding("utf-8");

                /**
                 * 以下是两种指定ftl文件所在目录路径的方式,注意这两种方式都是
                 * 指定ftl文件所在目录的路径,而不是ftl文件的路径
                 */
                
				configuration.setClassForTemplateLoading(this.getClass(), "");
                   
                //指定路径的第二种方式,我的路径是D:/Hard Disk E/DesKtop/
			    configuration.setDirectoryForTemplateLoading(new File("D:/Hard Disk E/DesKtop/"));

                //输出文档路径及名称
                String src_file = "";
                if (osName.toLowerCase().startsWith("win")) {
                    src_file = uploadWindows + "/zidongbaogao/";
                } else {
                    src_file = uploadLinux + "/zidongbaogao/";
                }
                File dir = new File(src_file);
                if (!dir.exists()) {
                    dir.mkdirs();
                }

				tring fileName ="我太帅了.doc";
                File outFile = new File(src_file + fileName);

                //以utf-8的编码读取ftl文件
				 Template template = configuration.getTemplate("根据厅办调研背景材料省模板060301.ftl", "utf-8");

                 Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8"));
//                  如果写入的变量有 ‘<’ '>' 需要替换一下  
//                  template.toString().replaceAll("<", "&lt;");
//                  template.toString().replaceAll(">", "&gt;");


 				Map<String,String> dataMap = new HashMap<String,String>();
                dataMap.put("name", "china");
                template.process(dataMap, out);
                out.close();
                
            }

        } catch (Exception e) {
            logger.error(e.getMessage());
        }
       
    }

原始的参考文档已经找不到了。。。
这里更完整一些 https://blog.csdn.net/Carolxiaobai/article/details/86479446

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值