文件下载:POI读取word或Excel,修改内容后以流的形式输出到前端

以下是WORD实例,此方案适用于EXCEL,不用使用绝对路径,对于数据安全有一定保障

/**
     * @author lcx
     * @param id    
     * @param request
     * @param response
     */
    @RequestMapping(value="/printhelp")
    public void printhelp(HttpServletRequest request ,HttpServletResponse response) {
        logger.info(null);
        String path = request.getRealPath("") + File.separatorChar;
        String filepath = path.concat("static/template/checkrepositorytemplate.doc");
        File fis=new File(filepath);
        InputStream in = null;
        try {
            in = new FileInputStream(fis);  
            HWPFDocument hdt = new HWPFDocument(in);
            Range range = hdt.getRange();

            Map<String, String> params = new HashMap<String, String>();
            params.put("${checkdate}",  "你好");
            params.put("${repaddress}",  "你好");
            params.put("${checkusers}",  "你好");
            params.put("${checkscope}",  "你好");
            params.put("${defects}",  "你好");
            params.put("${faded}",  "你好");
            params.put("${damage}", "你好");
            params.put("${mildew}",  "你好");
            params.put("${motheaten}",  "你好");
            params.put("${leaks}",  "你好");
            params.put("${exstate}", "你好");
            params.put("${takesteps}", "你好");
            //params.put("${note}",  dto.get("note")==null?"":dto.get("note").toString());
            //把word中包含params key的内容转换成value的内容
            for (Map.Entry<String,String> entry:params.entrySet()) {
                range.replaceText(entry.getKey(),entry.getValue());
            }

            response.reset();
            response.setContentType("application/x-msdownload");
            response.addHeader("Content-Disposition", "attachment; filename=\"" + "checkrepositorytemplate.doc" + "\"");

            ByteArrayOutputStream ostream = new ByteArrayOutputStream();
            ServletOutputStream servletOS = response.getOutputStream(); //输出流
            hdt.write(ostream);//数据写入到输出流           
            servletOS.write(ostream.toByteArray());         

            servletOS.flush();
            servletOS.close();
            ostream.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }finally{   
            try {
                in.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
评论 2
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值