extjs4+jxl实现grid按条件查询导出到Excel

来源:互联网 发布:linux修改eth0ip命令 编辑:程序博客网 时间:2024/06/06 02:56

用Extjs4做导出到excel时如果直接用form表单提交或者直接用Ext.Ajax.request提交数据后,页面对后台HttpServletResponse回来的数据被封装成response.responseText。但是我们需要页面弹出保存地址的对话框,因此不能直接异步调用。我的实现如下:

1.在页面写一个“导出”按钮,数据可以按照日期条件进行导出

{  iconCls: 'icon-export',  xtype:'button',  text : '导出',  handler: function(){    Ext.MessageBox.confirm("提示", "确认导出?", function(btn) {        if (btn == "yes") {            /*获取开始日期和结束日期*/            var start_time =Ext.util.Format.date(( Ext.getCmp("date_start").getValue()), 'Y-m-d');            var end_time = Ext.util.Format.date((Ext.getCmp("date_end").getValue()), 'Y-m-d');            /*直接提示给用户是否保存或打开此文档*/    window.location.href ='/xxx/xxxx/xxxxxx.do?queryInfo=export&startTime='+start_time +'&endTime='+end_time;          }    });   }}


2.后台jxl实现Excel导出功能

首先要在项目中引入jxl.jar包(可以点击转到这个页面下载http://download.csdn.net/detail/jingzizhu/4965670);按照日期查询条件将数据库查询结构放到一个list里面,再调用exportExcel方法

public void exportExcel(List<?> list, HttpServletRequest request, HttpServletResponse response) throws Exception { ServletOutputStream os = response.getOutputStream();try{DateFormat format = new SimpleDateFormat("yyyyMMddHHmmssSSS");String timeFileName = format.format(new Date());response.reset();response.setCharacterEncoding("GB2312");response.setContentType("application/octet-stream");response.setHeader("Content-Disposition", "attachment; filename=" + timeFileName + "_sysLog.xls"); // 创建工作薄WritableWorkbook wwb = Workbook.createWorkbook(os);// 创建工作表WritableSheet ws = wwb.createSheet("用户数据", 0);int row = 0, col = 0;// 第一行头部信息String[] head = new String[] { "用户名", "用户操作", "操作日期"};for (int i = 0; i < head.length; i++) {ws.addCell(new Label(col++, row, head[i]));}row++;for (int i = 0; i < list.size(); i++) {col = 0;Map<?, ?> str= (Map<?, ?>) list.get(i);ws.addCell(new Label(col++, row, str.get("user_name").toString()));ws.addCell(new Label(col++, row, str.get("user_operation").toString()));ws.addCell(new Label(col++, row, str.get("user_date").toString()));row++;}wwb.write();wwb.close();  } catch (Exception e) {e.printStackTrace();throw new Exception("生成excel出错!");  } finally {os.close();  }}



原创粉丝点击