导出datagrid中数据到Excel方法

  在各类系统中,经常要将系统数据导出制作报表以用来打印或汇报工作,本文以datagrid为例,阐述在工作中使用的一种导出技术

 JSP页面数据输出使用的是Jquery-easyUI的datagrid,给一个功能按钮用来进行导出操作      

<body class="easyui-layout">
	 <div data-options="region:'north',border:false,title:'查询条件'" iconCls="icon-searchQuery" collapsible="false" style="height:150px;padding:0px;overflow:hidden">
	 	 <form  id="searchForm" οnkeypress="onFormKeyPress(event)" method="post">
     		<table width="100%" class='searchTable' >
				 <tr>
					 <td align="right">姓名 :</td>
	                 <td align="left">
                 	 	<input type="text" name="name" id="name" style="width:200px"/> 
				     </td>
             </table>
          </form>
	 </div><!--end north-->
	 <div data-options="region:'center',border:false">
		<table id="gridTable" class="easyui-datagrid" title="列表信息(双击记录查看详情)" 
			data-options="rownumbers:true,idField:'id',sortName:'id',fit:true,pagination:true,singleSelect:false,url:'${ctx}/staff-file!list.do',method:'post',border:false,sortOrder:'desc',toolbar:'#tb',onDblClickRow:viewDetail">
		    <thead>
				<tr>
					<th data-options="field:'ck',checkbox:true"></th>
					<th data-options="field:'beCompanyName',fit:true,align:'center'">所属机构</th>	
					<th data-options="field:'name',fit:true,align:'center',sortable:true">姓名</th>	
					<th data-options="field:'staffCode',fit:true,align:'center',sortable:true">工号</th>	
					<th data-options="field:'positionName',fit:true,align:'center'">岗位</th>	
				</tr>
			</thead>
		</table>
		<div id="tb" style="padding:5px;height:auto">
			<a href="javascript:exportExcel('gridTable','searchForm','人员名单')" class="easyui-linkbutton" iconCls="icon-excel" plain="true" style="display:<g:button value='BUTTON_STAFFFILE_EXPORT'/>">导出</a>
		</div>
	 </div>
</body>

JS函数用来收集datagrid的数据

/**
 * 公用导出方法
 * dgID		:	datagrid表格ID
 * formID	:	查询条件表单ID
 * xlsName	:	导出的excel名字
 * filterName:	过滤的列名称
 */
function exportExcel(dgID,formID,xlsName,filterName){
	var opts = $('#'+dgID).datagrid('getColumnFields'); 
	var colNames= new Array();
	var fields  = new Array();
	for(var i=0 ; i < opts.length ; i++){
		var col = $('#'+dgID).datagrid("getColumnOption",opts[i]);
		if(col.title!=''&&col.title!=null){
			if(filterName==undefined){
				colNames.push(col.title);
				fields.push(col.field);
			}else{
				if(filterName.indexOf(col.title)<0){
					colNames.push(col.title);
					fields.push(col.field);
				}
			}
		}
	}
	//动态拼加input
	if($("#colNames").size()==0){
		$('#'+formID).append('<input name = "colNames" id="colNames" type="hidden"/>');
	}
	if($("#fields").size()==0){
		$('#'+formID).append('<input name = "fields" id="fields" type="hidden"/>');
	}
	if($("#xlsName").size()==0){
		$('#'+formID).append('<input name = "xlsName" id="xlsName" type="hidden"/>');
	}
	if($("#flgStr").size()==0){
		$('#'+formID).append('<input name = "flgStr" id="flgStr" type="hidden"/>');
	}
	//设置查询表单的action
	$('#'+formID).attr("action",$('#'+dgID).datagrid("options").url);
	//设置条件
	$("#colNames").val(colNames);
	$("#fields").val(fields);
	$("#xlsName").val(xlsName);
	$("#flgStr").val(1);
	$('#'+formID).submit();
	$("#flgStr").val('');	//置为空 
}

后台方法封装数据



后台方法输出Excel

/**
	 * 导出
	 * @param request
	 * @param response
	 * @param list
	 */
	public static void doExport(HttpServletRequest request,HttpServletResponse response,List<JSONObject> list){
		try {
			String colName     = request.getParameter("colNames");	//表头
			String field       = request.getParameter("fields");		//导出字段
			String xlsName     = request.getParameter("xlsName");		//导出文件名称
			String [] colNames = colName.split(",");
			String [] fields   = field.split(",");
			//导出
		    OutputStream os = response.getOutputStream();//取得输出流
		    response.reset();//清空输出流
		    //下面是对中文文件名的处理
		    response.setCharacterEncoding("UTF-8");//设置相应内容的编码格式
		    response.setHeader("Content-Disposition","attachment;filename="+new String(xlsName.getBytes("gb2312"),"iso-8859-1")+".xls");
		    response.setContentType("application/msexcel");//定义输出类型
		    
		    
		    WritableFont wf = new WritableFont(WritableFont.ARIAL, 10,
		    	     WritableFont.BOLD, false, UnderlineStyle.NO_UNDERLINE,
		    	     jxl.format.Colour.WHITE); // 定义格式 字体 下划线 斜体 粗体 颜色
		    WritableCellFormat wcf = new WritableCellFormat(wf); // 单元格定义
		    wcf.setBackground(jxl.format.Colour.GREEN); // 设置单元格的背景颜色
		    wcf.setAlignment(jxl.format.Alignment.CENTRE); // 设置对齐方式
		    wcf.setBorder(Border.ALL, BorderLineStyle.THIN);
		    //创建工作薄
	        WritableWorkbook workbook = Workbook.createWorkbook(os);
	        //创建新的一页
	        WritableSheet sheet = workbook.createSheet(xlsName, 0);
	        if (list.size()>0) {
	        	//设置表头
	        	for (int i = 0; i < colNames.length; i++) {
					Label lable = new Label(i, 0, colNames[i],wcf);
					sheet.addCell(lable);
					sheet.setColumnView(i, 20); // 设置列的宽度
				}
	        	
	        	for (int i = 0; i < list.size(); i++) {
	        		JSONObject jsonObject = list.get(i);
					for (int j = 0; j < colNames.length; j++) {
						Object value = jsonObject.get(fields[j]);
						
						Label lable = new Label(j, i+1, filter(value));
						sheet.addCell(lable);
					}
				}
			}
	        
	        //把创建的内容写入到输出流中,并关闭输出流
	        workbook.write();
	        workbook.close();
	        os.close();
		} catch (Exception e) {
			e.printStackTrace();
		}
		
	}



评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值