function exportExcel() {
    $.messager
            .confirm(
                    '提示信息',
                    '您确定要导出到Excel?',
                    function(r) {
                        if (r) {
                            var columns = $("#queryTmallTcMsgGrid").datagrid(
                                    "options").columns[0];
                            var stringTitle = "";
                            var stringFields = "";
                            for (var i = 0; i < columns.length; i++) {
                                //导出剔除'联系手机'
                                if (columns[i].title == "联系手机") {
                                    continue;
                                }
                                stringTitle = stringTitle + columns[i].title
                                        + ",";
                                if (columns[i].title == "客户性质") {
                                    stringFields = stringFields
                                            + "customerNatureName,";
                                } else if (columns[i].title == "是否回访") {
                                    stringFields = stringFields
                                            + "isCallbackName,";
                                } else if (columns[i].title == "是否购买") {
                                    stringFields = stringFields + "isBuyName,";
                                } else if (columns[i].title == "留言来源") {
                                    stringFields = stringFields
                                            + "messageSourceName,";
                                } else if (columns[i].title == "客户类型") {
                                    stringFields = stringFields
                                            + "userTypeName,";
                                } else if (columns[i].title == "分配类型") {
                                    stringFields = stringFields
                                            + "distributionTypeName,";
                                } else {
                                    stringFields = stringFields
                                            + columns[i].field + ",";
                                }
                            }
                            var queryParams = $("#queryTmallTcMsgGrid")
                                    .datagrid("options").queryParams;
                            queryParams.gridTitle = stringTitle;
                            queryParams.gridField = stringFields;
                            queryParams.moduleName = "天猫留言.xls";
                            var formObj = $("<form></form>")
                                    .attr("method", "post")
                                    .attr(
                                            "action",
                                            appPath
                                                    + "/page/tmallTcMessageAct/exportExcel");
                            formObj
                                    .append(
                                            "<input type='text' name='gridTitle'>")
                                    .append(
                                            "<input type='text' name='gridField'>")
                                    .append(
                                            "<input type='text' name='moduleName'>")
                                    .append(
                                            "<input type='text' name='tmallOrderId'>")
                                    .append(
                                            "<input type='text' name='memberName'>")
                                    .append(
                                            "<input type='text' name='alipayUserName'>")
                                    .append(
                                            "<input type='text' name='alipayPaidFee'>")
                                    .append(
                                            "<input type='text' name='message'>")
                                    .append(
                                            "<input type='text' name='messageSource'>")
                                    .append(
                                            "<input type='text' name='receiveUser'>")
                                    .append(
                                            "<input type='text' name='receiveFullAddress'>")
                                    .append(
                                            "<input type='text' name='receiveTel'>")
                                    .append(
                                            "<input type='text' name='receiveMobile'>")
                                    .append(
                                            "<input type='text' name='orderCreateTime'>")
                                    .append(
                                            "<input type='text' name='goodsNo'>")
                                    .append(
                                            "<input type='text' name='goodsTopic'>")
                                    .append(
                                            "<input type='text' name='goodsCount'>")
                                    .append(
                                            "<input type='text' name='isCallback'>")
                                    .append("<input type='text' name='isBuy'>")
                                    .append(
                                            "<input type='text' name='notBuyReason'>")
                                    .append(
                                            "<input type='text' name='callbackTime'>")
                                    .append(
                                            "<input type='text' name='commitUserid'>")
                                    .append(
                                            "<input type='text' name='callbackUserid'>")
                                    .append(
                                            "<input type='text' name='userType'>")
                                    .append(
                                            "<input type='text' name='serviceName'>")
                                    .append(
                                            "<input type='text' name='assignNum'>")
                                    .append(
                                            "<input type='text' name='distributionType'>")
                                    .append(
                                            "<input type='text' name='customerNature'>")
                                    .append(
                                            "<input type='text' name='bgMessageTime'>")
                                    .append(
                                            "<input type='text' name='endMessageTime'>")
                                    //8459修正
                                    /*.append(
                                            "<input type='text' name='importId'>")*/
                                    .append(
                                            "<input type='text' name='assignId'>")
                                    .append(
                                            "<input type='text' name = 'note'>")
                                    .append(
                                            "<input type='text' name = 'orderId'>")
                                    .css('display', 'none').appendTo("body");
                            formObj.form("load", queryParams);
                            formObj.submit();
                            formObj.remove();
                        }
                    });
}
@RequestMapping(value = "/exportExcel")
    public String exportExcel(HttpServletRequest request, HttpServletResponse response, TmallTcMessage tmallTcMessage) {

        String objList = "";
//        Integer userId = (Integer) request.getSession().getAttribute("userId");
//        Integer num = systemService.checkName(userId);
        Integer strLength = 4;
//        if (num != null && num > 0) {
//            strLength = 0;
//        }
        tmallTcMessage.setStrLength(strLength);
        try {
            objList = exportService.exportExcelFile(request,
                response,
                tmallTcMessage,
                "TmallTcMessage.TmallMessageExportExcel");
        } catch (Exception e) {
            logger.debug(e.getMessage());
            e.printStackTrace();
        }
        return objList;
    }

=============================================基类==========================================================================

    public String exportExcelFile(HttpServletRequest request,HttpServletResponse response,
            Object obj, String sqlMap) throws Exception {
        String fileChName = request.getParameter("moduleName");
        String gridTitle = request.getParameter("gridTitle");
        String gridField = request.getParameter("gridField");
        response.reset();
        response.setCharacterEncoding("ISO8859-1");
        response.setHeader("Content-Disposition", "attachment; filename="+new String(fileChName.getBytes("GBK"), "ISO8859-1"));//fileChName为下载时用户看到的文件名
        response.setHeader("Connection", "close");
        response.setHeader("Content-Type", "application/octet-stream");
        OutputStream out = response.getOutputStream();

        Map map = new HashMap();
        List<Object> paymentInfoList = commonDao.queryForList(sqlMap, obj);

        if(paymentInfoList.size()>10000){
            WritableWorkbook wbook = Workbook.createWorkbook(out);//直接写入内存,不要存放到硬盘中
            jxl.write.WritableSheet wsheet = wbook.createSheet("Sheet1", 0);//定义sheet的名称
            jxl.write.WritableFont wfont = null; // 字体
            jxl.write.WritableCellFormat wcfFC = null; // 字体格式
            jxl.write.Label wlabelString = null; // Excel表格的Cell,文本格式
            for(int i=0;i<1;i++){
                wsheet.setColumnView(i, 40);//设置列宽
            }
            // 设置excel标题字体
            wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD,
                false, jxl.format.UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
            wcfFC = new jxl.write.WritableCellFormat(wfont);
            wcfFC.setAlignment(jxl.format.Alignment.LEFT); // 设置对齐方式
            // 添加excel标题
            jxl.write.Label wlabel1 = new jxl.write.Label(5, 0,"导出提示",wcfFC);
            wsheet.addCell(wlabel1);
           // 设置正文字体
          wfont = new jxl.write.WritableFont(WritableFont.TIMES, 12, WritableFont.NO_BOLD,
            false, jxl.format.UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
          wcfFC = new jxl.write.WritableCellFormat(wfont);
          wcfFC.setAlignment(jxl.format.Alignment.LEFT); // 设置对齐方式
         //往Excel输出数据
          wlabelString = new jxl.write.Label(5, 1, "导出数据超过一万条,系统不支持,请分批导出",wcfFC);
          wsheet.addCell(wlabelString);
          wbook.write(); // 写入文件
          wbook.close();
          out.flush();
          out.close();
          return "ok";
        }

        String[] title = gridTitle.split(",");
        String[] propery = gridField.split(",");
        Integer titleNum = title.length;//Excel中字段的个数
        String FileTitle = "";//Excel中正文标题

        //--建立EXCEL索引、字段名、字段值的关系,存放到map中
        for(int i=0;i<title.length;i++){
            String PojoPropery =  propery[i];//grid中title和field是一一对应的,所以可以这么写
            String toUpp = PojoPropery.replaceFirst(PojoPropery.substring(0,1), PojoPropery.substring(0,1).toUpperCase());//把首字母转换为大写
            String methodName = "get"+toUpp;//拼成pojo类中getXXX的方法名称
            map.put(PojoPropery, new ExportExcelColumn(i,title[i],methodName));
        }

        this.export(out, FileTitle, titleNum,paymentInfoList, map);
        return "ok";
    }

==========================================================js=======================================================

//导出
function exportExcel(){
    $.messager.confirm('提示信息','您确定要导出到Excel?',function(r){
        if(r){
            var columns = $("#linksCommonGrid").datagrid("options").columns[0];

            //--------把标题grid标题和grid的field,拼接成字符串-----------
            var stringTitle = "";
            var stringFields = "";
            for(var i = 1; i < columns.length; i++){
                stringTitle = stringTitle + columns[i].title + ",";
                stringFields = stringFields + columns[i].field + ",";
            }
            if(stringTitle.lastIndexOf(",") == (stringTitle.length-1)){
                stringTitle = stringTitle.substring(0, stringTitle.lastIndexOf(","));
            }
            if(stringFields.lastIndexOf(",") == (stringFields.length-1)){
                stringFields = stringFields.substring(0, stringFields.lastIndexOf(","));
            }

            var queryParams = $("#linksCommonGrid").datagrid("options").queryParams;
            queryParams.gridTitle = stringTitle;
            queryParams.gridField = stringFields;
            queryParams.moduleName = "友情链接.xls";

            var formObj = $("<form></form>").attr("method","post").attr("action",appPath+"/page/pageIndexMrgAct/exportLinksList");
            formObj.append("<input type='text' name='gridTitle'>")
                   .append("<input type='text' name='gridField'>")
                   .append("<input type='text' name='moduleName'>")
                    .append("<input type='text' name='linkType'>")
                   .append("<input type='text' name='url'>")
                   .append("<input type='text' name='keywords1'>")
                   .append("<input type='text' name='linkUrl1'>")
                   .append("<input type='text' name='qq'>")
                   .append("<input type='text' name='keywords2'>")
                   .append("<input type='text' name='linkUrl2'>")
                   .css('display','none')
                   .appendTo("body");
            formObj.form("load",queryParams);
            formObj.submit();
            formObj.remove();
        }
    });
}

=====================================================java=======================================================

 /**
             * 导出excel
             *
             * @param request
             * @param response
             * @param website
             */
            @RequestMapping(value = "/exportLinksList")
            @ResponseBody
            public String exportLinksList(HttpServletRequest request,
                    HttpServletResponse response, PageIndexLinks pageIndexLinks) {
            try {
                    List<Object> LinksList=null;
                    ServiceMessage<List<Object>> res = pageIndexLinksService.getLinksListForExport(pageIndexLinks);
                    if(res.getStatus().getCode().equals("0")){
                    LinksList=res.getResult();
                        if(LinksList!=null && LinksList.size()>0){
                             Map<String,String> paramMap=new HashMap<String,String>();
                            String fileChName = request.getParameter("moduleName");
                            String gridTitle = request.getParameter("gridTitle");
                        String gridField = request.getParameter("gridField");
                            paramMap.put("moduleName", fileChName);
                            paramMap.put("gridTitle", gridTitle);
                            paramMap.put("gridField", gridField);
                        return     exportService.exportExcelFileSEO(response, paramMap, LinksList);
                        }
                    }
                } catch (Exception e) {
                e.printStackTrace();
                }
            return null;

            }

=========================基类===========================

/**
     * SEO daochu Excel
     */

    public String exportExcelFileSEO(HttpServletResponse response, Map<String,String> paramMap, List<Object> objList)throws Exception {
        String fileChName = paramMap.get("moduleName");
        String gridTitle = paramMap.get("gridTitle");
        String gridField = paramMap.get("gridField");
        response.reset();
        response.setCharacterEncoding("ISO8859-1");
        response.setHeader("Content-Disposition", "attachment; filename="+new String(fileChName.getBytes("GBK"), "ISO8859-1"));//fileChName为下载时用户看到的文件名
        response.setHeader("Connection", "close");
        response.setHeader("Content-Type", "application/octet-stream");
        OutputStream out = response.getOutputStream();
        Map map = new HashMap();

        if(objList.size()>10000){
            WritableWorkbook wbook = Workbook.createWorkbook(out);//直接写入内存,不要存放到硬盘中
            jxl.write.WritableSheet wsheet = wbook.createSheet("Sheet1", 0);//定义sheet的名称
            jxl.write.WritableFont wfont = null; // 字体
            jxl.write.WritableCellFormat wcfFC = null; // 字体格式
            jxl.write.Label wlabelString = null; // Excel表格的Cell,文本格式
            for(int i=0;i<1;i++){
                wsheet.setColumnView(i, 40);//设置列宽
            }
            // 设置excel标题字体
            wfont = new jxl.write.WritableFont(WritableFont.ARIAL, 14, WritableFont.BOLD,
                false, jxl.format.UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
            wcfFC = new jxl.write.WritableCellFormat(wfont);
            wcfFC.setAlignment(jxl.format.Alignment.LEFT); // 设置对齐方式
            // 添加excel标题
            jxl.write.Label wlabel1 = new jxl.write.Label(5, 0,"导出提示",wcfFC);
            wsheet.addCell(wlabel1);
           // 设置正文字体
          wfont = new jxl.write.WritableFont(WritableFont.TIMES, 12, WritableFont.NO_BOLD,
            false, jxl.format.UnderlineStyle.NO_UNDERLINE, jxl.format.Colour.BLACK);
          wcfFC = new jxl.write.WritableCellFormat(wfont);
          wcfFC.setAlignment(jxl.format.Alignment.LEFT); // 设置对齐方式
         //往Excel输出数据
          wlabelString = new jxl.write.Label(5, 1, "导出数据超过一万条,系统不支持,请分批导出",wcfFC);
          wsheet.addCell(wlabelString);
          wbook.write(); // 写入文件
          wbook.close();
          out.flush();
          out.close();
          return "ok";
        }

        String[] title = gridTitle.split(",");
        String[] propery = gridField.split(",");
        Integer titleNum = title.length;//Excel中字段的个数
        String FileTitle = "";//Excel中正文标题
        //--建立EXCEL索引、字段名、字段值的关系,存放到map中
        for(int i=0;i<title.length;i++){
            String PojoPropery =  propery[i];//grid中title和field是一一对应的,所以可以这么写
            String toUpp = PojoPropery.replaceFirst(PojoPropery.substring(0,1), PojoPropery.substring(0,1).toUpperCase());//把首字母转换为大写
            String methodName = "get"+toUpp;//拼成pojo类中getXXX的方法名称
            map.put(PojoPropery, new ExportExcelColumn(i,title[i],methodName));
        }

        this.export(out, FileTitle, titleNum,objList, map);
        return "ok";
    }

java基础之导出(Excel)的更多相关文章

  1. java基础篇 -- 导出excel表格数据

    本篇文章基于java把数据库中的数据以Excel的方式导出,欢迎各位大神吐槽: 1.基于maven jar包引入如下: <dependency> <groupId>net.so ...

  2. Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类

    Java 通过Xml导出Excel文件,Java Excel 导出工具类,Java导出Excel工具类 ============================== ©Copyright 蕃薯耀 20 ...

  3. java导入、导出Excel文件

    一.介绍 当前B/S模式已成为应用开发的主流,而在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用Excel打开(电信系统.银行系统).或者是:我们已经习惯用Excel打印.这样在我们实际 ...

  4. Java中导入导出Excel -- POI技术

    一.介绍: 当前B/S模式已成为应用开发的主流,而在企业办公系统中,常常有客户这样子要求:你要把我们的报表直接用Excel打开(电信系统.银行系统).或者是:我们已经习惯用Excel打印.这样在我们实 ...

  5. java五行代码导出Excel

    目录 先看代码 再看效果 EasyExcel 附: Java按模板导出Excel---基于Aspose实现 Java无模板导出Excel,Apache-POI插件实现 已经写过两种Excel导出插件了 ...

  6. java使用jxls导出Excel

    jxls是基于POI的Excel模板导出导入框架.通过使用类似于jstl的标签,有效较少导出Excel的代码量. 1.pom <!-- https://mvnrepository.com/art ...

  7. Java程序实现导出Excel,支持IE低版本

    来博客园两年多了,最近才开通了微博,因为懒所以也一直没有写东西,今天想整理一下自己前段时间遇到的一个导出的问题. 因为项目的需求,要做一部分导出功能.开始的时候用的公司的导出,但是很奇怪有部分模块导出 ...

  8. Java POI导入导出Excel

    1.异常java.lang.NoClassDefFoundError: org/apache/poi/UnsupportedFileFormatException 解决方法: 使用的poi的相关jar ...

  9. java基础之导入(Excel)2

    $(function(){ $("#linksCommonGrid").datagrid({ url:appPath+'/page/pageIndexMrgAct/queryPag ...

随机推荐

  1. 您为这个网络适配器输入的IP地址xxx.xxx.xxx.xx已经分配给另一个适配器xxx...

    您为这个网络适配器输入的IP地址xxx.xxx.xxx.xx已经分配给另一个适配器‘xxx NIC’.... 2008年11月03日 星期一 08:51 问题现象:   在网卡的TCP/IP属性中无法 ...

  2. 回传值(代理、通知、block)

    回传值问题,一直都是困扰初学者的问题,今写者 代理.通知.block 三者的回传值做了一个小小的总结, Main.storyboard 视图: 通过代码分别创建三个代表 代理.通知.block 的按钮 ...

  3. 武汉科技大学ACM:1008: 明明的随机数

    Problem Description 明明想在学校中请一些同学一起做一项问卷 调查,为了实验的客观性,他先用计算机生成了N个1到1000之间的随机整数(N≤100),对于其中重复的数字,只保留一个, ...

  4. 函数递归时,递归次数到900多时,就是抛出异常exception RuntimeError('maximum recursion depth exceeded',)

    import subprocess import multiprocessing import urllib import sys import os import pymongo import si ...

  5. CentOS 网络设置修改 指定IP地址 DNS 网关(转)

    CentOS 网络设置修改 指定IP地址 DNS 网关(实测 笔记)   环境: 系统硬件:vmware vsphere (CPU:2*4核,内存2G) 系统版本:Centos-6.5-x86_64 ...

  6. 以前5年只专注于.net,现今开始学习java.

    从2011年毕业至今一直在学习.net和c#,大概几年6月份底开始研究java了. 虽然不知道以后的路是否好走,但是我依然会努力.不放弃! 写这篇文字是为了鼓励自己,也为这段时光留下记忆.加油,红红!

  7. 转:40多个关于人脸检测/识别的API、库和软件

    文章来自于:http://blog.jobbole.com/45936/ 自从谷歌眼镜被推出以来,围绕人脸识别,出现了很多争议.我们相信,不管是不是通过智能眼镜,人脸识别将在人与人交往甚至人与物交互中 ...

  8. spark1.1.0源码阅读-executor

    1. executor上执行launchTask def launchTask( context: ExecutorBackend, taskId: Long, taskName: String, s ...

  9. Android 之 Spinner

    1:activity_main.xml <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/androi ...

  10. Thread 1 cannot allocate new log的问题分析

    http://blog.csdn.net/zonelan/article/details/7613519 http://leoguan.blog.51cto.com/816378/584494 htt ...