easyui导出Excel、Word java

问题描述:easyui datagrid导出Excel,使用java后台适用于多个页面
解决方案:第一:在含有datagrid的界面exportPage.jsp中引用js(主要用于获取datagrid数据以及转换为html格式)
代码为:<script type="text/javascript" src="<%=request.getContextPath()%>/js/export.js"></script>
第二:在exportPage.jsp的javascritp编辑中设置变量var grid='';var exportString='';并且在<body></body>之间添加一个div,主要用于弹出对话框,选择导出格式:代码:<div id="dialog2"></div> 
第三:将exportPage.jsp的datagrid初始化时赋值于grid,
代码为:
<span style="white-space:pre">	</span>grid=$('#dg').datagrid({
				url:.....,
				toolbar: [{
					text:'Export',
					iconCls: 'icon-excel',//自定义的css样式图片
					handler: function(){
					expt(grid);
					}
				},'-']
			});


第四:export.js的代码为:
function expt(grid){
		var tableString = '<table cellspacing="0" class="pb">';  
    		var frozenColumns = grid.datagrid("options").frozenColumns;  // 得到frozenColumns对象  
   		var columns = grid.datagrid("options").columns;    // 得到columns对象  
    		var nameList = new Array();  
  
    // 载入title  
    if (typeof columns != 'undefined' && columns != '') {  
        $(columns).each(function (index) {  
            tableString += '\n<tr>';  
            if (typeof frozenColumns != 'undefined' && typeof frozenColumns[index] != 'undefined') {  
                for (var i = 0; i < frozenColumns[index].length; ++i) {  
                    if (!frozenColumns[index][i].hidden) {  
                        tableString += '\n<th width="' + frozenColumns[index][i].width + '"';  
                        if (typeof frozenColumns[index][i].rowspan != 'undefined' && frozenColumns[index][i].rowspan > 1) {  
                            tableString += ' rowspan="' + frozenColumns[index][i].rowspan + '"';  
                        }  
                        if (typeof frozenColumns[index][i].colspan != 'undefined' && frozenColumns[index][i].colspan > 1) {  
                            tableString += ' colspan="' + frozenColumns[index][i].colspan + '"';  
                        }  
                        if (typeof frozenColumns[index][i].field != 'undefined' && frozenColumns[index][i].field != '') {  
                            nameList.push(frozenColumns[index][i]);  
                        }  
                        tableString += '>' + frozenColumns[0][i].title + '</th>';  
                    }  
                }  
            }  
            for (var i = 0; i < columns[index].length; ++i) {  
                if (!columns[index][i].hidden) {  
                    tableString += '\n<th width="' + columns[index][i].width + '"';  
                    if (typeof columns[index][i].rowspan != 'undefined' && columns[index][i].rowspan > 1) {  
                        tableString += ' rowspan="' + columns[index][i].rowspan + '"';  
                    }  
                    if (typeof columns[index][i].colspan != 'undefined' && columns[index][i].colspan > 1) {  
                        tableString += ' colspan="' + columns[index][i].colspan + '"';  
                    }  
                    if (typeof columns[index][i].field != 'undefined' && columns[index][i].field != '') {  
                        nameList.push(columns[index][i]);  
                    }  
                    tableString += '>' + columns[index][i].title + '</th>';  
                }  
            }  
            tableString += '\n</tr>';  
        });  
    }  
    // 载入内容  
    var rows = grid.datagrid("getRows"); // 这段代码是获取当前页的所有行  
    for (var i = 0; i < rows.length; ++i) {  
        tableString += '\n<tr>';  
        for (var j = 0; j < nameList.length; ++j) {  
            var e = nameList[j].field.lastIndexOf('_0');  
  
            tableString += '\n<td';  
            if (nameList[j].align != 'undefined' && nameList[j].align != '') {  
                tableString += ' style="text-align:' + nameList[j].align + ';"';  
            }  
            tableString += '>';  
            if (e + 2 == nameList[j].field.length) {  
                tableString += rows[i][nameList[j].field.substring(0, e)];  
            }  
            else  
                tableString += rows[i][nameList[j].field];  
            tableString += '</td>';  
        }  
        tableString += '\n</tr>';  
    }  
    tableString += '\n</table>'; 
    $('#hlf').val(tableString);
    exportString=tableString;
    var url="../export.jsp";
    var param2={
			doSize:false,
			shadow:false,
			content:'<iframe  scrolling="no" frameborder="0"  src="'+url+'" style="width:100%;height:95%;"></iframe>',
			title:'Export',
		    width:300,    
		    height:170,
		    modal:true   	
	};
	mpgdialog(param2);
} 


function mpgdialog(param){	
		$('#dialog2').dialog(param);
		$('#dialog2').window('center');
	}




第五:export.jsp代码为:
<?xml version="1.0" encoding="UTF-8" ?>
<%@ page language="java" contentType="text/html; charset=UTF-8"
    pageEncoding="gb2312"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<link rel="stylesheet" type="text/css" href="<%=request.getContextPath()%>/js/easyui/themes/default/easyui.css">
<script type="text/javascript" src="<%=request.getContextPath()%>/js/easyui/jquery.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/easyui/jquery.easyui.min.js"></script>
<script type="text/javascript" src="<%=request.getContextPath()%>/js/common/init.js"></script>
<script type="text/javascript">
//var currTabId=parent.currTabId;
//var parentObj=parent.$("#"+currTabId)[0].contentWindow;
window.οnlοad=function(){
	document.getElementById("hlf").value=parent.exportString;
};


function btnExcel(){
	document.getElementById("type").value="excel";
	document.getElementById("formAction").submit();
}
function btnWord(){
	document.getElementById("type").value="word";
	document.getElementById("formAction").submit();
}
</script>
</head>
<body style="padding:20px; align:center" >
     <form id='formAction' action="<%=request.getContextPath()%>/Export.do"  method="post">
     	<font size="3px">Please select the type of export for export ......</font><br /><br />
     	<input id="dgg" class="easyui-linkbutton" type="button" value="Excel" οnclick="btnExcel()"/>
     	<input id="dgg" class="easyui-linkbutton" type="button" style="margin-left:50px;" value="Word" οnclick="btnWord()"/>
 		<input id="hlf" name='hfs'  type="hidden"/>
 		<input id="type" name='type'  type="hidden"/>
    </form>
</body>
</html>


第五:后台代码为:
package com.ieslab.eim.login.action;


import java.io.IOException;
import java.io.PrintWriter;
import java.io.UnsupportedEncodingException;


import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;


import org.apache.struts.action.Action;
import org.apache.struts.action.ActionForm;
import org.apache.struts.action.ActionForward;
import org.apache.struts.action.ActionMapping;


public class Export extends Action{
	public ActionForward execute(ActionMapping actionMapping,
            ActionForm actionForm,
            HttpServletRequest request,
            HttpServletResponse response) {  
		 	response.reset();
		 	try {
		 		request.setCharacterEncoding("UTF-8");
		 	} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
		 		e1.printStackTrace();
		 	}
			String hf=request.getParameter("hfs");
			String type=request.getParameter("type");
			String exportname="grid";
			try {
				if(type.equals("excel"))
		        {
		    	    exportname+=".xls";
					response.setHeader("Content-disposition", "attachment; filename="+java.net.URLEncoder.encode(exportname, "UTF-8")+"");
		        	response.setContentType("application/msexcel;charset=utf-8");
		        }
		        else if(type.equals("word"))
		        {
		        	exportname+=".doc";
		        	response.setHeader("Content-disposition", "attachment; filename="+java.net.URLEncoder.encode(exportname, "UTF-8")+"");
		        	response.setContentType("application/ms-word;charset=UTF-8");
		        }
			} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
				e.printStackTrace();
			}
		    PrintWriter out;
			try {
				out = response.getWriter();
				out.println(hf);
				out.close();
			} catch (IOException e) {
				// TODO Auto-generated catch block
				e.printStackTrace();
			}
			return actionMapping.findForward("failure");
	 }


}




  • 2
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 3
    评论
评论 3
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值