数据以Excel表导出

前端页面是freemarker循环遍历的集合,通过点击事件获取到所有数据,组合成一个字符串,发送到后台,后台建立Excel对象,并写入,注意前端页面点击事件的最后字符串一定是以form表单提交的方式提交到后台,否则控制器处理完,浏览器不弹出选择保存路径的弹出框,ajax也不行;

$("#export").click(function () {

            var tr=$("#datatable tr");
            var result=[];
            for (var i=0;i<tr.length;i++){
                var tds=$(tr[i]).find("td");
                if(tds.length>0){
                    result.push({'rindex':$(tds[0]).html(),'consignee':$(tds[1]).html(),'phoneList':$(tds[2]).html(),'sum':$(tds[3]).html(),'first':$(tds[4]).html(),'end':$(tds[5]).html()} );
                }
            }
            //把字符串给表单的input hidden  
            $("#customerInformation").val(JSON.stringify(result));

            var url = "${base}/eleC/exportExcel";
            //改变form表单的action,并提交给后台;
            $("#queryForm").attr("action", url);
            $("#queryForm").submit();


            //var customerInformation=JSON.stringify(result);
            /*$.ajax({
                type:"post",
                url:"",
                data:{"customerInformation":customerInformation},
                dataType:"text",
                success:function(result){
                    alert(result);
                    //layer.msg(result.data.message);
                }
            })*/
                }
        );

后台处理

public String exportExcel(ElmClient condition,String customerInformation,Model model) throws Exception{
        // 建立一个Excel
        Workbook book=new HSSFWorkbook();
        // 在对应的Excel中建立一个分表
        Sheet sheet1=(Sheet)book.createSheet("分表1");
        // 设置相应的行(初始从0开始)
        Row row=sheet1.createRow(0);
        // 在所在的行设置所在的单元格(相当于列,初始从0开始,对应的就是A列)
        Cell cell=row.createCell(0);
        // 写入相关数据到设置的行列中去。
        //cell.setCellValue("客户信息");
        // 创建单元格,设置值表头,设置表头居中
        CellStyle style = book.createCellStyle();
        // 居中格式
        style.setAlignment(HSSFCellStyle.ALIGN_CENTER);//水平居中
        style.setVerticalAlignment(HSSFCellStyle.VERTICAL_CENTER);//垂直居中
        sheet1.setDefaultColumnStyle(0, style);
        sheet1.setDefaultColumnStyle(1, style);
        sheet1.setDefaultColumnStyle(2, style);
        sheet1.setDefaultColumnStyle(3, style);
        sheet1.setDefaultColumnStyle(4, style);
        sheet1.setDefaultColumnStyle(5, style);
        sheet1.setColumnWidth(2, 20 * 256);
        sheet1.setColumnWidth(4, 20 * 256);
        sheet1.setColumnWidth(5, 20 * 256);
        //第一行永远是我们前面页面显示的标题
        cell = row.createCell(0);
        cell.setCellValue("#");
        cell.setCellStyle(style);

        cell = row.createCell(1);
        cell.setCellValue("客户姓名");
        cell.setCellStyle(style);

        cell = row.createCell(2);
        cell.setCellValue("电话");
        cell.setCellStyle(style);

        cell = row.createCell(3);
        cell.setCellValue("下单次数");
        cell.setCellStyle(style);

        cell = row.createCell(4);
        cell.setCellValue("第一次下单时间");
        cell.setCellStyle(style);

        cell = row.createCell(5);
        cell.setCellValue("最近下单时间");
        cell.setCellStyle(style);

        List<ElmExcel> datas =JSON.parseArray(customerInformation,ElmExcel.class);
        // 循环将数据写入Excel
        for (int i = 0; i < datas.size(); i++) {
            row = sheet1.createRow( i + 1);
            ElmExcel elmExcel=datas.get(i);
            // 创建单元格,设置值
            row.createCell(0).setCellValue(elmExcel.getRindex());//#

            row.createCell(1).setCellValue(elmExcel.getConsignee());//客户姓名

            row.createCell(2).setCellValue(elmExcel.getPhoneList());//电话

            row.createCell(3).setCellValue(elmExcel.getSum());//下单次数

            row.createCell(4).setCellValue(elmExcel.getFirst());//第一次下单时间

            row.createCell(5).setCellValue(elmExcel.getEnd());//最近下单时间

        }



        SimpleDateFormat df = new SimpleDateFormat("yyyyMMdd");//设置日期格式,HH:mm:ss
        // new Date()为获取当前系统时间
        String fileName = String.valueOf(df.format(new Date()))+"客户信息"+ ".xls";
        String userAgent = request.getHeader("User-Agent");
        if (/* IE 8 至 IE 10 */
                userAgent.toUpperCase().contains("MSIE") ||
                        /* IE 11 */
                        userAgent.contains("Trident/7.0")
                ) {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        } else if (
                userAgent.toUpperCase().contains("MOZILLA") ||
                        userAgent.toUpperCase().contains("CHROME")
                ) {
            fileName = new String(fileName.getBytes(), "ISO-8859-1");
        } else {
            fileName = URLEncoder.encode(fileName, "UTF-8");
        }

        response.setCharacterEncoding("UTF-8");
        response.addHeader("Content-Disposition", "attachment;filename=" + fileName);
        response.setContentType("application/vnd.ms-excel");//;charset=gb2312
        OutputStream os= response.getOutputStream();
        book.write(os);
        os.flush();
        os.close();
        //返回你点击导出信息后想跳转的页面去       
        return test(condition,model);
    }

猜你喜欢

转载自my.oschina.net/Skynet01/blog/1809992