java使用poi,导出数据致word模板,以提供下载。

首先制定word模板,改成你需要的样子。格式如下,$需要变量名称$。使用poi。

从前台传值过来:window.location.href = basePath + '**.do?id='+encodeURI(encodeURI(id, "UTF-8"),"UTF-8");

    //获取模板文件的目录地址
        String path = request.getSession().getServletContext().getRealPath("/");
        String fileDir = new File(path+"jsp/templet/").getCanonicalPath();

    //获取模板文件
        File demoFile=new File(fileDir + "/doc.doc");

    FileInputStream in = new FileInputStream(demoFile);
        HWPFDocument hdt = new HWPFDocument(in);
        //替换读取到的word模板内容的指定字段
        Range range = hdt.getRange();
        Map<String, String> map = new HashMap<String, String>();
        map.put("$BIANMA$", SSCID);
        map.put("$DENAME$", DNAME);
        map.put("$DATE$", now.get(Calendar.YEAR)+"年"+(now.get(Calendar.MONTH) + 1)+"月"+now.get(Calendar.DAY_OF_MONTH)+"日");
        for (Map.Entry<String,String> entry:map.entrySet()) {
            range.replaceText(entry.getKey(),entry.getValue());
        }
        
        //输出word内容文件流,提供下载
        response.setContentType("application/x-msdownload");
        String name = java.net.URLEncoder.encode(DNAME+".doc", "UTF8");
        name = new String((name).getBytes("UTF-8"), "ISO-8859-1");
        response.addHeader("Content-Disposition", "attachment; filename*=utf-8'zh_cn'"+name);
        ByteArrayOutputStream ostream = new ByteArrayOutputStream();
        ServletOutputStream servletOS = response.getOutputStream();
        hdt.write(ostream);
        servletOS.write(ostream.toByteArray());
        servletOS.flush();
        servletOS.close();

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值