Java后台生成Excel前台下载

Java后台通过poi生成HSSFWorkbook
对生成HSSFWorkbook 类型处理 转为文件流通过response 返回到前台

HSSFWorkbook hw = null;
        try{
            hw = ex.export();  //execl 工具类,生成HSSFWorkbook;
        }catch (Exception e){
            e.printStackTrace();
        }
        OutputStream fos = null;
        try {
            fos = response.getOutputStream();
            String userAgent = request.getHeader("USER-AGENT");
            String fileName = "居民信息";
            try {
                if(StringUtils.contains(userAgent, "Mozilla")){
                    fileName = new String(fileName.getBytes(), "ISO8859-1");
                }else {
                    fileName = URLEncoder.encode(fileName, "utf8");
                }
            } catch (UnsupportedEncodingException e) {
                e.printStackTrace();
            }
		//设置response返回信息
            response.setCharacterEncoding("UTF-8");
            response.setContentType("application/vnd.ms-excel;charset=utf-8");// 设置contentType为excel格式
            response.setHeader("Content-Disposition", "Attachment;Filename="+ fileName+".xls");
            hw.write(fos);
            fos.close();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

前端使用form表单提交,不能使用ajax请求;

function downloadFile(actoinURL,map){
    var form = $("<form></form>");
    $('#toExcelBtn').append(form);
    form.attr('style','display:none');
    form.attr('target','');
    form.attr('method','get');
    form.attr('action',actoinURL);//下载文件的请求路径
    var input1 = $('<input>');
    input1.attr('type','hidden');
    input1.attr('name','name');
    input1.attr('value',map.name);
    form.append(input1);
     form.submit(); //提交表单
 }

隐藏的form 与input,在input中设置参数值;
下载事件调用该方法 ;
然后浏览器自动下载到默认路径;

猜你喜欢

转载自blog.csdn.net/naihe0420/article/details/84673846