easyui datagrid to excel

 1 $.extend($.fn.datagrid.methods, {
 2     toExcel: function(jq, filename){
 3         return jq.each(function(){
 4             var uri = 'data:application/vnd.ms-excel;base64,'
 5             , template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" xmlns="http://www.w3.org/TR/REC-html40"><head><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>'
 6             , base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
 7             , format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
 8 
 9             var alink = $('<a style="display:none"></a>').appendTo('body');
10             var view = $(this).datagrid('getPanel').find('div.datagrid-view');
11             var table = view.find('div.datagrid-view2 table.datagrid-btable').clone();
12             var tbody = table.find('>tbody');
13             view.find('div.datagrid-view1 table.datagrid-btable>tbody>tr').each(function(index){
14                 $(this).clone().children().prependTo(tbody.children('tr:eq('+index+')'));
15             });
16             var ctx = { worksheet: name || 'Worksheet', table: table.html()||'' };
17             alink[0].href = uri + base64(format(template, ctx));
18             alink[0].download = filename;
19             alink[0].click();
20             alink.remove();
21         })
22     }
23 });

 

posted @ 2015-09-02 15:22  少爵  阅读(1614)  评论(0编辑  收藏  举报