使用freemarker生成word,excel

废话不多说,直接进入正题。

  • 编写一个word模板

091418_ezvN_2984644.png 

  • 将word模板另存为xml文件

091554_geQc_2984644.png

  • 使用notepad++打开,格式化下,这里只截取其中的一部分

091744_F6Wd_2984644.png

  • 找到需要替换的词,替换如下

091954_wTjk_2984644.png

替换如下

092033_GDhG_2984644.png

如果是表格,需要用到freemarker的<#list>标签

找到相应位置,替换如下:

092611_M2Yg_2984644.png

092619_mD3t_2984644.png

后面的也是如此,照这样替换,记得要有结束标签</#list>

  • 替换完之后另存为ftl文件

092803_wwEa_2984644.png

  • 接下来就是代码了
@Test
    public void test1() throws IOException, TemplateException {
        /** 初始化配置文件 **/
        Configuration configuration = new Configuration();
        /** 设置编码 **/
        configuration.setDefaultEncoding("utf-8");
        /** 我的ftl文件是放在D盘的**/
        String fileDirectory = "D:\\";
        /** 加载文件 **/
        configuration.setDirectoryForTemplateLoading(new File(fileDirectory));
        /** 加载模板 **/
        Template template = configuration.getTemplate("excel.ftl");
        /** 准备数据 **/
        Map<String,Object> dataMap2 = new HashMap<String,Object>();
        OderDetail oderDetail = new OderDetail("12312", "张三", new BigDecimal(123), new BigDecimal(123), new BigDecimal(12321), "123", "213", "12312", "213");
        OderDetail oderDetail2 = new OderDetail("12312", "张三", new BigDecimal(123), new BigDecimal(123), new BigDecimal(12321), "123", "213", "12312", "213");
        OderDetail oderDetail3 = new OderDetail("12312", "张三", new BigDecimal(123), new BigDecimal(123), new BigDecimal(12321), "123", "213", "12312", "213");
        OderDetail oderDetail4 = new OderDetail("12312", "张三", new BigDecimal(123), new BigDecimal(123), new BigDecimal(12321), "123", "213", "12312", "213");
        ArrayList<OderDetail> oderDetails = new ArrayList<OderDetail>();
        oderDetails.add(oderDetail);
        oderDetails.add(oderDetail2);
        oderDetails.add(oderDetail3);
        oderDetails.add(oderDetail4);
        dataMap2.put("orderNo","10000012312");
        dataMap2.put("wareHouseNumber","21323123");
        dataMap2.put("rkDate","2017-01-22");
        dataMap2.put("wareHouse","好仓库");
        dataMap2.put("supplier","卡斯柯");
        dataMap2.put("pList", oderDetails);
 


        /** 指定输出word文件的路径 **/
        String outFilePath = "D:\\myFreeMarker.xls";
        File docFile = new File(outFilePath);
        FileOutputStream fos = new FileOutputStream(docFile);
        Writer out = new BufferedWriter(new OutputStreamWriter(fos, "utf-8"),10240);
        template.process(dataMap2,out);

        if(out != null){
            out.close();
        }
    }

相应的,也可以对excel进行这样的操作,代码不用改变。

转载于:https://my.oschina.net/u/2984644/blog/853280

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值