freemarker生成word

生成通用的报告模板

一、先制作ftl文件(一定要用word,wps生成会有问题)

  1. 先在新建的word中写入模板
    在这里插入图片描述
  2. 另存为xml文件
    在这里插入图片描述
  3. 将xml文件更名为ftl文件
  4. 更改ftl文件中的内容
    全局搜索,将变量替换,图片是base64形式的。
    我们设定了三个变量,title,content,image64
    在这里插入图片描述
    二、将ftl文件转成word文件
    将ftl文件放在src的com.kaisnm.template目录下。
package com.kaisnm.util;

import java.io.BufferedWriter;
import java.io.File;
import java.io.FileOutputStream;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.io.Writer;
import java.util.HashMap;
import java.util.Map;

import freemarker.template.Configuration;
import freemarker.template.Template;
import freemarker.template.TemplateException;

public class DocumentHandler {
	private Configuration configuration = null;

	public DocumentHandler() {
		configuration = new Configuration();
		configuration.setDefaultEncoding("utf-8");
	}

	/**
	 * 
	 * @param dataMap 要填入模板的数据文件 HashMap<String,Object>()
	 * @param templatePath 要填入模板文件路径 "/com/kaisnm/template"
	 * @param templateName 要填入模板文件名称
	 * @param outPath 输出文件的路径
	 */
	public void createDocXml(Map dataMap, String templatePath,String templateName, String outPath) {
		configuration.setClassForTemplateLoading(this.getClass(), templatePath);
		Template t = null;
		try {
			t = configuration.getTemplate(templateName);
		} catch (IOException e) {
			e.printStackTrace();
		}
		// 输出文档路径及名称
		File outFile = new File(outPath);
		Writer out = null;
		try {
			out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
		} catch (Exception e1) {
			e1.printStackTrace();
		}
		try {
			t.process(dataMap, out);
		} catch (TemplateException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}
	public static void main(String[] args) {
		DocumentHandler documentHandler = new DocumentHandler();
		Map<String,String> map = new HashMap<>();
		//base64:格式:  data:image/png;base64,xxx*** ,我们需要的是xxx***字符串 
		String image64 = "";
		map.put("title","这个是我要的标题");
		map.put("content","这个是我要的内容");
		map.put("image64",image64);
		documentHandler.createDocXml(map, "/com/kaisnm/template", "test.ftl", "bb.doc");
	}
}

运行main函数
在指定的目录下生成了bb.doc,生成word完成
在这里插入图片描述

三、报告中需要使用echart的图表,我们需要获取echart的base64图片

<script type="text/javascript">
    // 路径配置 获取echart的库
    require.config({
        paths: {
            echarts: 'http://***/lib/echart/dist',
        }
    });
    // 使用
    require(
        [
            'echarts',
            'echarts/theme/macarons',
            'echarts/chart/bar',// 使用柱状图就加载bar模块,按需加载
            'echarts/chart/line'// 使用直线
        ],
        function (ec) {
            // 基于准备好的dom,初始化echarts实例
            var myChart = ec.init(document.getElementById('myChart1'));
            var option = {
                animation: false,
                tooltip: {
                    trigger: 'axis'
                },
                calculable: true,
                xAxis: [
                    {
                        axisLabel: {
                            rotate: 30,
                        },
                        type: 'category',
                        data: [1, 2, 3, 4, 5, 6, 7, 8, 9, 0] //初始化echart的数据
                    }
                ],
                yAxis: [
                    {
                        type: 'value'
                    }
                ],
                series: [
                    {
                        name: '销售额',
                        type: 'bar',
                        data: [2, 3, 4, 5, 6, 7, 8, 9, 0]
                    }
                ]
            };

            // 使用刚指定的配置项和数据显示图表。
            myChart.setOption(option);
            document.getElementById('image1Url').value = myChart.getDataURL('png');
        }
    );
</script>

document.getElementById(‘image1Url’).value = myChart.getDataURL(‘png’);
通过myChart.getDataURL(‘png’) 获取echarts的base64图片,再传入后台生成word文件即可。

注意:
生成word就只是使用freemarker的一个工具方法,如果生成的文件打不开,可能是参数原因。如果你的参数是个list,也可以在ftl文件中遍历出来。

使用freemarker生成word ,并集成struts2 同时生成及下载文档 资料附有Java源代码和自己总结的使用说明及注意事项 大至预览如下: 1、用word编辑好模板 普通字符串替换为 ${string} 表格循环用标签 姓名:${user.userName} , 性别:${user.sex} 2、将word模板另存为xml格式 3、将xml模板文件后缀名改为.ftl 4、编辑ftl文件 注意 编辑word模板时,${string} 标签最好是手动一次性输入完毕,或者使用记事本统一将整个${string}编辑好之后,粘贴至word里边。 也就是说,不要在word里首先打完 ${ } 之后,又从其它地方把 string 字符串粘贴至 { } 之间,这样在 word 转化为 xml时,解析会有问题,freemarker解析时,会报错。 /** * @Desc:生成word文件 * @Author:张轮 * @Date:2014-1-22下午05:33:42 * @param dataMap word中需要展示的动态数据,用map集合来保存 * @param templateName word模板名称,例如:test.ftl * @param filePath 文件生成的目标路径,例如:D:/wordFile/ * @param fileName 生成的文件名称,例如:test.doc */ @SuppressWarnings("unchecked") public static void createWord(Map dataMap,String templateName,String filePath,String fileName){ try { //创建配置实例 Configuration configuration = new Configuration(); //设置编码 configuration.setDefaultEncoding("UTF-8"); //ftl模板文件统一放至 com.lun.template 包下面 configuration.setClassForTemplateLoading(WordUtil.class,"/com/lun/template/"); //获取模板 Template template = configuration.getTemplate(templateName); //输出文件 File outFile = new File(filePath+File.separator+fileName); //如果输出目标文件夹不存在,则创建 if (!outFile.getParentFile().exists()){ outFile.getParentFile().mkdirs(); } //将模板和数据模型合并生成文件 Writer out = new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile),"UTF-8")); //生成文件 template.process(dataMap, out); //关闭流 out.flush(); out.close(); } catch (Exception e) { e.printStackTrace(); } }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

kaisnm

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

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

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

打赏作者

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

抵扣说明:

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

余额充值