利用JQuery实现web页面中table导出excel的功能

实现办法下载jquery的excel导出插件点击打开链接,此插件需要base64编码,所以在引用的时候也需要在引用64位编码的js脚本,例如

   <script src="jquery-1.10.2.js"></script>
    <script src="tableExport.js"></script>
    <script src="jquery.base64.js"></script>

使用方法:

<button type="button" οnclick="$('#tb_doc_m').tableExport({ type: 'excel', separator: ';', escape: 'false' });"  class="btn btn-default">
            <i class="glyphicon glyphicon-search">导出Excel</i>
        </button>
<table class="table" id="tb_doc_m">

.....

</table>


如果要导出表头需要设置完整的table,如thread,tbody等标准的html5表格。

额外注意:由于下载的脚本无法解决中文导出问题所以需要修改base64编码的js脚本,以及在tableexport使用base64编码脚本的部分。

已经修改完成的脚本如下:

http://download.csdn.net/detail/huangyezi/8782953

或者:

001 (function($){
002         $.fn.extend({
003             tableExport: function(options) {
004                 var defaults = {
005       separator: ',',
006       ignoreColumn: [],
007       tableName:'yourTableName',
008       type:'csv',
009       pdfFontSize:14,
010       pdfLeftMargin:20,
011       escape:'true',
012       htmlContent:'false',
013       consoleLog:'false'
014     };
015                   
016     var options = $.extend(defaults, options);
017     var el = this;
018       
019     if(defaults.type == 'csv' || defaults.type == 'txt'){
020       
021      // Header
022      var tdData ="";
023      $(el).find('thead').find('tr').each(function() {
024      tdData += "\n";    
025       $(this).filter(':visible').find('th').each(function(index,data) {
026        if ($(this).css('display') != 'none'){
027         if(defaults.ignoreColumn.indexOf(index) == -1){
028          tdData += '"' + parseString($(this)) + '"' + defaults.separator;        
029         }
030        }
031          
032       });
033       tdData = $.trim(tdData);
034       tdData = $.trim(tdData).substring(0, tdData.length -1);
035      });
036        
037      // Row vs Column
038      $(el).find('tbody').find('tr').each(function() {
039      tdData += "\n";
040       $(this).filter(':visible').find('td').each(function(index,data) {
041        if ($(this).css('display') != 'none'){
042         if(defaults.ignoreColumn.indexOf(index) == -1){
043          tdData += '"'+ parseString($(this)) + '"'+ defaults.separator;
044         }
045        }
046       });
047       //tdData = $.trim(tdData);
048       tdData = $.trim(tdData).substring(0, tdData.length -1);
049      });
050        
051      //output
052      if(defaults.consoleLog == 'true'){
053       console.log(tdData);
054      }
055      var base64data = "base64," + $.base64.encode(tdData);
056      window.open('data:application/'+defaults.type+';filename=exportData;' + base64data);
057     }else if(defaults.type == 'sql'){
058       
059      // Header
060      var tdData ="INSERT INTO `"+defaults.tableName+"` (";
061      $(el).find('thead').find('tr').each(function() {
062        
063       $(this).filter(':visible').find('th').each(function(index,data) {
064        if ($(this).css('display') != 'none'){
065         if(defaults.ignoreColumn.indexOf(index) == -1){
066          tdData += '`' + parseString($(this)) + '`,' ;        
067         }
068        }
069          
070       });
071       tdData = $.trim(tdData);
072       tdData = $.trim(tdData).substring(0, tdData.length -1);
073      });
074      tdData += ") VALUES ";
075      // Row vs Column
076      $(el).find('tbody').find('tr').each(function() {
077      tdData += "(";
078       $(this).filter(':visible').find('td').each(function(index,data) {
079        if ($(this).css('display') != 'none'){
080         if(defaults.ignoreColumn.indexOf(index) == -1){
081          tdData += '"'+ parseString($(this)) + '",';
082         }
083        }
084       });
085         
086       tdData = $.trim(tdData).substring(0, tdData.length -1);
087       tdData += "),";
088      });
089      tdData = $.trim(tdData).substring(0, tdData.length -1);
090      tdData += ";";
091        
092      //output
093      //console.log(tdData);
094        
095      if(defaults.consoleLog == 'true'){
096       console.log(tdData);
097      }
098        
099      var base64data = "base64," + $.base64.encode(tdData);
100      window.open('data:application/sql;filename=exportData;' + base64data);
101        
102       
103     }else if(defaults.type == 'json'){
104       
105      var jsonHeaderArray = [];
106      $(el).find('thead').find('tr').each(function() {
107       var tdData ="";
108       var jsonArrayTd = [];
109        
110       $(this).filter(':visible').find('th').each(function(index,data) {
111        if ($(this).css('display') != 'none'){
112         if(defaults.ignoreColumn.indexOf(index) == -1){
113          jsonArrayTd.push(parseString($(this)));        
114         }
115        }
116       });        
117       jsonHeaderArray.push(jsonArrayTd);     
118         
119      });
120        
121      var jsonArray = [];
122      $(el).find('tbody').find('tr').each(function() {
123       var tdData ="";
124       var jsonArrayTd = [];
125        
126       $(this).filter(':visible').find('td').each(function(index,data) {
127        if ($(this).css('display') != 'none'){
128         if(defaults.ignoreColumn.indexOf(index) == -1){
129          jsonArrayTd.push(parseString($(this)));        
130         }
131        }
132       });        
133       jsonArray.push(jsonArrayTd);        
134         
135      });
136        
137      var jsonExportArray =[];
138      jsonExportArray.push({header:jsonHeaderArray,data:jsonArray});
139        
140      //Return as JSON
141      //console.log(JSON.stringify(jsonExportArray));
142        
143      //Return as Array
144      //console.log(jsonExportArray);
145      if(defaults.consoleLog == 'true'){
146       console.log(JSON.stringify(jsonExportArray));
147      }
148      var base64data = "base64," + $.base64.encode(JSON.stringify(jsonExportArray));
149      window.open('data:application/json;filename=exportData;' + base64data);
150     }else if(defaults.type == 'xml'){
151       
152      var xml = '<?xml version="1.0" encoding="utf-8"?>';
153      xml += '<tabledata><fields>';
154      // Header
155      $(el).find('thead').find('tr').each(function() {
156       $(this).filter(':visible').find('th').each(function(index,data) {
157        if ($(this).css('display') != 'none'){    
158         if(defaults.ignoreColumn.indexOf(index) == -1){
159          xml += "<field>" + parseString($(this)) + "</field>";
160         }
161        }
162       });        
163      });    
164      xml += '</fields><data>';
165        
166      // Row Vs Column
167      var rowCount=1;
168      $(el).find('tbody').find('tr').each(function() {
169       xml += '<row id="'+rowCount+'">';
170       var colCount=0;
171       $(this).filter(':visible').find('td').each(function(index,data) {
172        if ($(this).css('display') != 'none'){
173         if(defaults.ignoreColumn.indexOf(index) == -1){
174          xml += "<column-"+colCount+">"+parseString($(this))+"</column-"+colCount+">";
175         }
176        }
177        colCount++;
178       });              
179       rowCount++;
180       xml += '</row>';
181      });    
182      xml += '</data></tabledata>'
183        
184      if(defaults.consoleLog == 'true'){
185       console.log(xml);
186      }
187        
188      var base64data = "base64," + $.base64.encode(xml);
189      window.open('data:application/xml;filename=exportData;' + base64data);
190     }else if(defaults.type == 'excel' || defaults.type == 'doc'|| defaults.type == 'powerpoint'  ){
191          
192      var excel="<table>";
193      // Header
194      $(el).find('thead').find('tr').each(function() {
195       excel += "<tr>";
196       // $(this).filter(':visible')
197       $(this).find('th').each(function(index,data) {
198        if ($(this).css('display') != 'none'){    
199         if(defaults.ignoreColumn.indexOf(index) == -1){
200             var colspan = $(this).attr('colspan');
201             if(!colspan) colspan = 1;
202             excel += "<td style='text-align: center; vertical-align: middle;' colspan='" + colspan + "'>" + parseString($(this))+ "</td>";
203         }
204        }
205       });
206       // $(this).filter(':visible')
207       $(this).find('td').each(function(index,data) {
208           if ($(this).css('display') != 'none'){    
209            if(defaults.ignoreColumn.indexOf(index) == -1){
210             var colspan = $(this).attr('colspan');
211             var rowspan = $(this).attr('rowspan');
212             if(!colspan) colspan = 1;
213             if(!rowspan) rowspan = 1;
214             excel += "<td style='text-align:center;' colspan='" + colspan + "' rowspan='" + rowspan + "'>" + parseString($(this))+ "</td>";
215            }
216           }
217          });
218       excel += '</tr>';     
219      });    
220        
221        
222      // Row Vs Column
223      var rowCount=1;
224      $(el).find('tbody').find('tr').each(function() {
225       excel += "<tr>";
226       var colCount=0;
227       // $(this).filter(':visible')
228       $(this).find('td').each(function(index,data) {
229        if ($(this).css('display') != 'none'){
230         if(defaults.ignoreColumn.indexOf(index) == -1){
231             var rowspan = $(this).attr('rowspan');
232             if(!rowspan) rowspan = 1;
233          excel += "<td rowspan='" + rowspan + "' style='color:" + $(this).css('color') + "'>"+parseString($(this))+"</td>";
234         }
235        }
236        colCount++;
237       });              
238       rowCount++;
239       excel += '</tr>';
240      });    
241      excel += '</table>'
242        
243      if(defaults.consoleLog == 'true'){
244       console.log(excel);
245      }
246        
247      var excelFile = "<html xmlns:o='urn:schemas-microsoft-com:office:office' xmlns:x='urn:schemas-microsoft-com:office:"+defaults.type+"' xmlns='http://www.w3.org/TR/REC-html40'>";
248      excelFile += "<head>";
249      excelFile += "<!--[if gte mso 9]>";
250      excelFile += "<xml>";
251      excelFile += "<x:ExcelWorkbook>";
252      excelFile += "<x:ExcelWorksheets>";
253      excelFile += "<x:ExcelWorksheet>";
254      excelFile += "<x:Name>";
255      excelFile += "{worksheet}";
256      excelFile += "</x:Name>";
257      excelFile += "<x:WorksheetOptions>";
258      excelFile += "<x:DisplayGridlines/>";
259      excelFile += "</x:WorksheetOptions>";
260      excelFile += "</x:ExcelWorksheet>";
261      excelFile += "</x:ExcelWorksheets>";
262      excelFile += "</x:ExcelWorkbook>";
263      excelFile += "</xml>";
264      excelFile += "<![endif]-->";
265      excelFile += "</head>";
266      excelFile += "<body>";
267      excelFile += excel;
268      excelFile += "</body>";
269      excelFile += "</html>";
270      var base64data = "base64," + $.base64({ data: excelFile, type: 0 });
271      //window.open('data:application/vnd.ms-'+defaults.type+';filename=exportData.doc;' + base64data);
272      $('<a style="display:none" href="data:application/vnd.ms-'+defaults.type+';filename=exportData.doc;'+base64data+'" download="'+defaults.tableName.toString()+'.xls"><span></span></a>').appendTo(document.body).find('span').trigger("click").parent().remove();
273     }else if(defaults.type == 'png'){
274      html2canvas($(el), {
275       onrendered: function(canvas) {         
276        var img = canvas.toDataURL("image/png");
277        window.open(img);
278          
279          
280       }
281      }); 
282     }else if(defaults.type == 'pdf'){
283    
284      var doc = new jsPDF('p','pt''a4'true);
285      doc.setFontSize(defaults.pdfFontSize);
286        
287      // Header
288      var startColPosition=defaults.pdfLeftMargin;
289      $(el).find('thead').find('tr').each(function() {
290       $(this).filter(':visible').find('th').each(function(index,data) {
291        if ($(this).css('display') != 'none'){    
292         if(defaults.ignoreColumn.indexOf(index) == -1){
293          var colPosition = startColPosition+ (index * 50);        
294          doc.text(colPosition,20, parseString($(this)));
295         }
296        }
297       });        
298      });    
299       
300       
301      // Row Vs Column
302      var startRowPosition = 20; var page =1;var rowPosition=0;
303      $(el).find('tbody').find('tr').each(function(index,data) {
304       rowCalc = index+1;
305         
306      if (rowCalc % 26 == 0){
307       doc.addPage();
308       page++;
309       startRowPosition=startRowPosition+10;
310      }
311      rowPosition=(startRowPosition + (rowCalc * 10)) - ((page -1) * 280);
312         
313       $(this).filter(':visible').find('td').each(function(index,data) {
314        if ($(this).css('display') != 'none'){
315         if(defaults.ignoreColumn.indexOf(index) == -1){
316          var colPosition = startColPosition+ (index * 50);        
317          doc.text(colPosition,rowPosition, parseString($(this)));
318         }
319        }
320          
321       });              
322         
323      });    
324             
325      // Output as Data URI
326      doc.output('datauri');
327    
328     }
329       
330       
331     function parseString(data){
332       
333      if(defaults.htmlContent == 'true'){
334       content_data = data.html().trim();
335      }else{
336       content_data = data.text().trim();
337      }
338        
339      if(defaults.escape == 'true'){
340       content_data = escape(content_data);
341      }
342        
343        
344        
345      return content_data;
346     }
347      
348    }
349         });
350     })(jQuery);

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值