首頁  >  文章  >  web前端  >  jquery匯出資料到excel程式碼實例詳解

jquery匯出資料到excel程式碼實例詳解

伊谢尔伦
伊谢尔伦原創
2017-07-22 09:25:592427瀏覽

DataTables是一個jQuery的表格外掛。這是一個高度靈活的工具,依據的基礎逐步增強,這將增加先進的互動控制,支援任何HTML表格。主要特點:

不過可惜的是官方網站表格資料匯出方法使用的是tabletools插件,利用flash匯出數據,而且不支援中文數據,透過尋找官方的API和資料,找到使用jquery和php導出資料方法。

匯出資料的javascript函數


function table2csv(oTable, exportmode, tableElm) { 
    var csv = ''; 
    var headers = []; 
    var rows = []; 
    // Get header names 
    $(tableElm+' thead').find('th').each(function() { 
      var $th = $(this); 
      var text = $th.text(); 
      var header = '"' + text + '"'; 
      // headers.push(header); // original code 
      if(text != "") headers.push(header); // actually datatables seems to copy my original headers so there ist an amount of TH cells which are empty 
    }); 
    csv += headers.join(',') + "\n"; 
    // get table data 
    if (exportmode == "full") { // total data 
      var total = oTable.fnSettings().fnRecordsTotal() 
      for(i = 0; i < total; i++) { 
        var row = oTable.fnGetData(i); 
        row = strip_tags(row); 
        rows.push(row); 
      } 
    } else { // visible rows only 
      $(tableElm+&#39; tbody tr:visible&#39;).each(function(index) { 
        var row = oTable.fnGetData(this); 
        row = strip_tags(row); 
        rows.push(row); 
      }) 
    } 
    csv += rows.join("\n"); 
    // if a csv p is already open, delete it 
    if($(&#39;.csv-data&#39;).length) $(&#39;.csv-data&#39;).remove(); 
    // open a p with a download link 
    $(&#39;body&#39;).append(&#39;<p class="csv-data"><form enctype="multipart/form-data" method="post" action="/csv.php"><textarea class="form" name="csv">&#39;+csv+&#39;</textarea><input type="submit" class="submit" value="Download as file" /></form></p>&#39;); 
} 
function strip_tags(html) { 
  var tmp = document.createElement("p"); 
  tmp.innerHTML = html; 
  return tmp.textContent||tmp.innerText; 
}

函數支援匯出所有資料和目前頁資料


// export only what is visible right now (filters & paginationapplied)
$(&#39;#export_visible&#39;).click(function(event) {  
   var oTable; 
   oTable= $(&#39;#spdata&#39;).dataTable(); 
   event.preventDefault(); 
   table2csv(oTable, &#39;visible&#39;, &#39;#spdata&#39;); })
   // export all table data 
$(&#39;#export_all&#39;).click(function(event) {  
  var oTable; 
  oTable= $(&#39;#spdata&#39;).dataTable(); 
  event.preventDefault(); 
 table2csv(oTable, &#39;full&#39;, &#39;#spdata&#39;); })

其中#spdata是table的id 

後台php匯出excel程式碼


#
header("Content-Type: application/vnd.ms-execl");  
header("Content-Disposition: attachment; filename=myExcel.csv");  
header("Pragma: no-cache");  
header("Expires: 0");  
$buffer = $_POST[&#39;csv&#39;];     
$buffer=str_replace(",",",\t",$buffer); 
$buffer=mb_convert_encoding($buffer,"GB2312","UTF-8");  
echo $buffer;

以上是jquery匯出資料到excel程式碼實例詳解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn