导出word文档开发-freemarker

1.pom.xml

	<dependency>
      <groupId>org.freemarker</groupId>
      <artifactId>freemarker</artifactId>
      <version>2.3.28</version>
 	</dependency>
  • 这里版本号自己控制(各版本差异自行百度)
  • https://mvnrepository.com/artifact/org.freemarker/freemarker

2.word模板

已WPS为例

  1. 打开需要开发导出的word文档
  2. 另存为 选择其他格式 选择XML格式 保存
  3. 在项目资源文件夹新建 **.ftl 文件
  4. 把另存的xml文件内容贴近 **.ftl 文件(或直接把xml扔进项目里改名)
    word内容
//导出的xml里对应模板信息
<w:r>
	<w:rPr>
		<w:rFonts w:hint="fareast"/>
		<w:lang w:val="EN-US" w:fareast="ZH-CN"/>
	</w:rPr>
	<w:t>姓名:</w:t>
</w:r>

3.代码

	/**
     * 使用FreeMarker通过模版生成word文档,模版文件需存放在/properties文件夹下
     * @param docData 模版中使用的数据
     * @param ftlName 模版文件的名称,只能是ftl类型文件
     * @param filePath 生成的doc文件存放的位置
     * @param fileName 生成的doc文件的名称(不含扩展名)
     * @return
     * @throws IOException
     */
    public void createDoc(Map<String, Object> docData, String ftlName, String filePath, String fileName) throws IOException {
        // FreeMarker模板配置对象
        Configuration configuration = new Configuration(Configuration.VERSION_2_3_22);
        // 指定模版文件目录
        configuration.setClassLoaderForTemplateLoading(this.getClass().getClassLoader(), "/properties");
        // 指定模版字符集
        configuration.setDefaultEncoding("UTF-8");
        // 加载模板文件
        Template tmplt = configuration.getTemplate(ftlName);
        // 生成doc文件的名称
        String docName = filePath + fileName + ".doc";
        // 待doc文件
        File docFile = null;
        try {
            docFile = new File(docName);
            Writer opWriter = new OutputStreamWriter(new FileOutputStream(docFile), "utf-8");
            tmplt.process(docData, opWriter);
            opWriter.flush();
            opWriter.close();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

4.FreeMarker基础语法

//同EL表达式 ${name}   // 这些基本都能解决了,如遇到不能解决的自行百度
	1.if语句(判断是否为空)  
  <#if target?? >  
    此处为iftrue的内容
  </#if>

  2.list循环
  <#list list as t>
    ${t.title}
  </#list>

5.建议

//建议加上非空判断   不建议直接使用 ${name} 来展示 不加判断 值为空的话会报错
<w:r>
	<w:rPr>
		<w:rFonts w:hint="fareast"/>
		<w:lang w:val="EN-US" w:fareast="ZH-CN"/>
	</w:rPr>
	<w:t>姓名: <#if name??  && name != "">
					${name}
				<#else> 
				
				</#if>
	</w:t>
</w:r>

6.参考网站

http://freemarker.foofun.cn/ 或直接百度

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值