页面Excel导出超详细版

熊大是第一写博客,有一些成长的经验很想与各位撰码人分享,若有不对之处还望各位大佬指教。

这篇很适合初学者,从头到尾很详细,跟着一步一步来完全没有任何问题的。

先介绍一下熊大此次写的内容大致业务逻辑(从页面上导出Excle字段为门店名称,门店地址,品牌的表格,方便用户使用)

咱们先得在XML里面写好查询的sql(用的是Mybatis框架)

 <select id="exportStore" resultMap="result">
        select
        s.name as store_name ,
        s.address as store_address ,
        og.name as org_name
        from t_product_store_org_package p, t_store s, t_store_org_package so,t_org og
        where p.store_org_package_id = so.id AND s.id = so.store_id AND s.org_id=og.id
        <if test="_parameter != null and _parameter !='' ">
            AND p.product_id = #{_parameter} ORDER BY og.sort
        </if>
    </select>

在映射类写好与XML相对应的接口,用于Service调用,方法名与XML查询的id要保持一致

public List<ProductStoreOrgPackage> exportStore(String productId);

ServiceImpl的方法,也就是导出的整个核心代码

public String findExportStore(String productId) {
        String ret = url;
        //生成一个工作薄
        HSSFWorkbook workbook = new HSSFWorkbook();
        //创建一个工作薄片
        HSSFSheet sheet = workbook.createSheet("关联门店数据单");
        //设置列宽
        sheet.setDefaultColumnWidth(15);
        //生成一个样式
        HSSFCellStyle style = workbook.createCellStyle();
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平
        //生成表格的标题的行
        HSSFRow header = sheet.createRow(0);
        //设置页眉
        header.createCell(0).setCellValue("品牌");
        header.createCell(1).setCellValue("门店昵称");
        header.createCell(2).setCellValue("门店地址");
        OSSClient client = null;
        try {
            //取到通过查询条件得到的数据
            List<ProductStoreOrgPackage> psList = productStoreOrgPackageMapper.exportStore(productId);
            if (CollectionUtils.isEmpty(psList)) {  //如果查询得到的数据为空 ,则返回null 以防万一
                return null;
            }
            int rowNum = 1; //  定义rowNum为1 因为下标为0的为标题行
            for (ProductStoreOrgPackage rc : psList) {  //循环遍历psList
                HSSFRow row = sheet.getRow(rowNum); //得到行
                if (row == null) {  //如果不为空则创建列
                    row = sheet.createRow(rowNum);
                }
                row.createCell(0).setCellValue(rc.getOrgname());  //设置列的数据为从实体类得到的数据
                row.createCell(1).setCellValue(rc.getStoreName());
                row.createCell(2).setCellValue(rc.getAddress());
                rowNum++;
            }
            client = osSimpleClient.createOSSClient();   //以下代码都为上次到阿里云的模板
            ByteArrayOutputStream os = new ByteArrayOutputStream();
            workbook.write(os);
            String bucketName = "backend-finance-bucket";
            String key = System.currentTimeMillis() + ".xls";
            if (!client.doesBucketExist(bucketName)) {
                client.createBucket(bucketName);
            }
            client.setBucketAcl(bucketName, CannedAccessControlList.PublicRead);
            PutObjectResult result = client.putObject(bucketName, key, new ByteArrayInputStream(os.toByteArray()));
            logger.debug("文件地址是:" + result.getETag() + " key: " + key);
            os.close();
            ret += key;    //key是阿里云自动生成的一个标识  唯一的
        } catch (Exception e) {
            logger.error("导出预约列表失败:", e);
            return "500";
        } finally {
            osSimpleClient.closeClient(client);
            try {
                workbook.close();
            } catch (IOException ex) {
                ex.printStackTrace();
                return null;
            }
        }
        return ret;
    }

Service接口

  public String findExportStore(String productId);

Controller    

@RequestMapping("/exportstore")
    @ResponseBody
    public Object exportstore(String productId) {
        ResponseResult rtn = new ResponseResult();
        try {
             //取到导出关联门店的数据
            String url = productService.findExportStore(productId);
            if (StringUtils.isEmpty(url)) {
                rtn = new ResponseResult(ResponseResult.Status.FAILED.getCode(), "没有数据可以导出!");
            } else if ("500".equals(url)) {
                rtn = new ResponseResult(ResponseResult.Status.FAILED.getCode(), "导出发生异常,请与管理员联系!");
            } else {
                rtn.setResult(url);// 导出成功,返回Excel的下载地址
            }
        } catch (Exception ex) {
            ex.printStackTrace();b
            rtn = new ResponseResult(ResponseResult.Status.FAILED.getCode(), "导出失败,请与管理员联系!");
        }

        return doCallback(rtn, request.getParameter("callback"));
    }

Jsp页面的button

<a class="button" href="#" id="exportStore" url="${ctx}/biz/proMgt/exportstore?productId=${productId}">导出</a>

Js页面

  request为封装的Ajax 

url:请求的url地址

type:请求的类型,可以是:GET|POST,但是如果dataType参数指为jsonp的话,这里设置为POST没有任何意义,因为jsonp只能是GET

dataType
要求为String类型的参数,预期服务器返回的数据类型。如果不指定,JQuery将自动根据http包mime信息返回responseXML或responseText,并作为回调函数参数传递。可用的类型如下:
xml:返回XML文档,可用JQuery处理。
html:返回纯文本HTML信息;包含的script标签会在插入DOM时执行。
script:返回纯文本JavaScript代码。不会自动缓存结果。除非设置了cache参数。注意在远程请求时(不在同一个域下),所有post请求都将转为get请求。
json:返回JSON数据。
jsonp:JSONP格式。使用SONP形式调用函数时,例如myurl?callback=?,JQuery将自动替换后一个“?”为正确的函数名,以执行回调函数。

text:返回纯文本字符串。

showSuccessMsg:服务器调用成功时是否弹窗提示

showServerErrorMsg:服务器调用失败时是否弹窗提示

showErrorMsg:Ajax调用失败时是否弹窗提示

serverErrorMsgTime:服务器调用失败时弹窗的停留时间(默认2秒)

onSuccess:服务器调用成功时的回调接口方法

contentType:要求为String类型的参数,当发送信息至服务器时,内容编码类型默认为"application/x-www-form-urlencoded"。该默认值适合大多数应用场合。

processData要 求为Boolean类型的参数,默认为true。默认情况下,发送的数据将被转换为对象(从技术角度来讲并非字符串)以配合默认内容类 型"application/x-www-form-urlencoded"。如果要发送DOM树信息或者其他不希望转换的信息,请设置为false。

clasself = this;
    $("#exportStore").on('click', function () {
        var url = $(this).attr("url");
        clasself.request({
            url: url,
            type: 'post',
            dataType: 'json',
            showSuccessMsg: true,
            showServerErrorMsg: true,
            serverErrorMsgTime: 2,
            showErrorMsg: true,
            contentType: false,
            processData: false,
            onSuccess: function (rtn) {
                if (rtn.code < 0) {
                    clasself.tips(rtn.message, 2);
                } else {
                    location.href = rtn.result;
                    clasself.tips('导出成功!', 2, function () {
                        window.location.reload();
                    });
                }
            }
        });

    })

有各种问题,欢迎评论。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值