FreeMarker生成word

本文介绍如何使用Java和FreeMarker实现定时生成包含图片和文字的Word文档,详细讲解了从定义模板到执行spring定时任务的整个流程。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

引言

java后台代码,定时生成word,可包含图片,文字,表格等。本文只用到图片,文字。

技术指标

  • FreeMarker
  • jar包:freemarker-2.3.13.jar
  • spring定时任务

过程概述

1.先定义好word模板,编辑好样式,另存为xml;
2.打开xml,用 {text}, imgbase64 {}替换;
3.将xml后缀名改为ftl文件;
4.准备数据;
5.执行程序,填充数据,保存成doc文件;
6.方法放入spring定时任务中。

主要代码

## 生成word代码 ##
public class DocFreeMarker {
    private Configuration configuration = null;

        public DocFreeMarker() {
            configuration = new Configuration();
            configuration.setDefaultEncoding("UTF-8");
        }

        public String getImageStr(String imgFile){
            InputStream in=null;
            byte[] data=null;
            try {
                //in=new FileInputStream(imgFile);
                if(imgFile.indexOf("http")==0){
                    URL url = new URL(imgFile);
                    //in = url.openStream();
                    URLConnection connection = url.openConnection();
                    connection.connect();
                    in = connection.getInputStream();
                }else if(imgFile.length()>0){
                    in = new FileInputStream(imgFile);
                }

                data=new byte[in.available()];
                in.read(data);
                in.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }
            BASE64Encoder encoder=new BASE64Encoder();
            return encoder.encode(data);
        }

        public void createDoc(Map<String,Object> dataMap,String downloadType,String savePath){
            try {
                //加载需要装填的模板
                Template template=null;
                //设置模板装置方法和路径,FreeMarker支持多种模板装载方法。可以重servlet,classpath,数据库装载。
                //加载模板文件,放在testDoc下
                configuration.setClassForTemplateLoading(this.getClass(), "/com/zhwy/auto/template");
                //设置对象包装器
    //            configure.setObjectWrapper(new DefaultObjectWrapper());
                //设置异常处理器
                configuration.setTemplateExceptionHandler(TemplateExceptionHandler.IGNORE_HANDLER);
                //定义Template对象,注意模板类型名字与downloadType要一致,xml和ftl好像都可以。
                template = configuration.getTemplate(downloadType+".ftl","UTF-8");
                File outFile = new File(savePath);
                Writer out=null;
                out=new BufferedWriter(new OutputStreamWriter(new FileOutputStream(outFile), "UTF-8"));
                template.process(dataMap, out);
                if(out!=null){
                    out.flush();
                    out.close();
                }
                //out.close();
            } catch (IOException e) {
                e.printStackTrace();
            } catch (TemplateException e) {
                e.printStackTrace();
            }
        }
           public Map<String,Object> createData(){
               Map<String,Object> dataMap = new HashMap<String, Object>();
               dataMap.put("RAIN_1H_TEXT", "从20日18时到19时,保定、沧州及以南的大部地区出现降雨天气");
               dataMap.put("RAIN_3H_TEXT", "从20日18时到19时,保定、沧州及以南的大部地区出现降雨天气。");
               dataMap.put("RAIN_6H_TEXT", "从20日18时到19时,保定、沧州及以南的大部地区出现降雨天气。");
               dataMap.put("RAIN_12H_TEXT", "从20日18时到19时,保定、沧州及以南的大部地区出现降雨天气。");
               dataMap.put("RAIN_24H_TEXT", "从20日18时到19时,保定、沧州及以南的大部地区出现降雨天气。");

               dataMap.put("RAIN_1H_IMG", getImageStr("E:\\FreeMarker\\1.png"));
               dataMap.put("RAIN_3H_IMG", getImageStr("E:\\FreeMarker\\3.png"));
               dataMap.put("RAIN_6H_IMG", getImageStr("E:\\FreeMarker\\6.png"));
               dataMap.put("RAIN_12H_IMG", getImageStr("E:\\FreeMarker\\12.png"));
               dataMap.put("RAIN_24H_IMG", getImageStr("E:\\FreeMarker\\24.png"));

               return dataMap;
       }
       public void createWord1() {
            DocFreeMarker test = new DocFreeMarker();
            Map<String, Object> dataMap = test.createData();
            String downloadType = "RainKuaiBao";
            long time = System.currentTimeMillis();
            String savePath = "E:/FreeMarker/RainKuaiBao" + time + ".doc";
            test.createDoc(dataMap, downloadType, savePath);
        }

        public static void main(String[] args) {
            DocFreeMarker dfm = new DocFreeMarker();
            dfm.createWord1();
        }
}
## spring定时任务代码 ##
@Component
public class ProductAutoTask {

    @Autowired
    private ProductAuto ProductAuto;

    @Scheduled(cron="0 10 * * * ?") //秒 分钟 小时 天 月 星期 年
    public void test(){
        System.out.println("<<<*****自动生成雨情快报定时任务开始*****>>>");
        ProductAuto.docAuto_rainKuaiBao();
        System.out.println("<<<---------雨情快报生成结束--------->>>");
    }

}

srping配置:
<beans
    xmlns:task="http://www.springframework.org/schema/task"
    xsi:schemaLocation="http://www.springframework.org/schema/task
           http://www.springframework.org/schema/task/spring-task-3.1.xsd"
>
    <!-- 增加定时任务插件 -->
    <context:annotation-config></context:annotation-config>
    <!-- 开启这个配置 spring才能识别@Scheduled注解 -->
    <task:annotation-driven scheduler="qbScheduler" mode="proxy"/>
    <task:scheduler id="qbScheduler" pool-size="10"/>

踩过的坑

  1. word模板中应添完全不一样的图片,要不然,保存成xml的时候,只会找到一处被base64编码的位置。
  2. 程序中必须替换ftl中定义的${}标签,并且内容不能为null,可以为空“”,若是图片,生成的word,扔保留图片的位置。

参考资料

1.FreeMarker之概念介绍 http://blog.youkuaiyun.com/y_love_f/article/details/41595647
2.FreeMarker三宗罪 http://www.iteye.com/topic/17468

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

打赏作者

songhuageini

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

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

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

打赏作者

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

抵扣说明:

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

余额充值