最近遇到一个问题,需要用easyui 导出exel,下面是方法:需要四个参数,
1.JSONData-datagrid的数据 直接获取到datagrid的所有行 然后转成json就行了 我是这样做的:var data = JSON.stringify($('#productDetail').datagrid('getRows'));
2.columnOptions - 列名的数组
/* 获取所有列名 */
var opt = $('#productDetail').datagrid('getColumnFields'); //这是获取到所有的FIELD
var columnOptions=[];
for(i=0;i<opt.length;i++)
{
var col = $('#productDetail').datagrid( "getColumnOption" , opt[i]);
columnOptions.push(col);//把TITLEPUSH到数组里去
}
3.url 需要提交到后台的路径,就是form表单的路径
4.title 导出文件的文件名
/**
* @requires jQuery
* 页面导出excel
* 解析为cvs
*/
var JSONToCSVConvertor =function(JSONData,columnOptions,url,title) {
var arrData = typeof JSONData != 'object' ? JSON.parse(JSONData) : JSONData;
var CSV = '';
if(true) {
var row = "";
for ( var i = 0; i < columnOptions.length; i ++) {
row += columnOptions[i].title + ',';
}
row = row.slice(0, -1);
CSV += row + '\r\n';
}
for (var i = 0; i < arrData.length; i++){
var row = "";
for ( var j= 0; j< columnOptions.length; j++)
{
row += '"' + arrData[i][columnOptions[j].field] + '",';
}
row.slice(0, row.length - 1);
CSV += row + '\r\n';
}
if (CSV == '') {
alert("Invalid data");
return;
}
$('#hd_excel_data') .val(CSV) ;
$('#hd_excel_title') .val(title) ;
$('#fm_excel_export').form({
url:url,
onSubmit: function(){
// do some check
// return false to prevent submit;
},
success:function(data){
}
});
$('#fm_excel_export').submit();
return;
}
下面是form表单,将datagrid数据提交到后台,进行转码,解决乱码问题
<form id="fm_excel_export" >
<input type = "hidden" id = "hd_excel_data" name = "data" >
<input type = "hidden" id = "hd_excel_title" name = "title" >
</form>
后台很简单:
@Controller
@RequestMapping("/util.do")
public class UtilsController {
@RequestMapping("/csv")
public void convertDataToCSV(HttpServletRequest request,HttpServletResponse response) throws IOException{
//加上UTF-8文件的标识字符
String data=new String(request.getParameter("data").getBytes("ISO-8859-1"),"UTF-8");
OutputStreamWriter out = new OutputStreamWriter(response.getOutputStream(), "GBK");
response.setCharacterEncoding("GBK");
response.setContentType("application/ms-excel");
response.setHeader("Content-Disposition", "attachment;filename="+new String(request.getParameter("title").getBytes("ISO-8859-1"),"UTF-8"));
// out.write("< meta http - equiv =\"content-type\" content=\"application/vnd.ms-excel; charset=utf-8\"/>");
// out.write(new String(new byte []{( byte ) 0xEF ,( byte ) 0xBB ,( byte ) 0xBF }));
out.write(data);
out.flush();
}
}