DataTables is a jQuery table plug-in. This is a highly flexible tool based on progressive enhancements that will add advanced interactive controls and support for any HTML form. Main features:
However, it is a pity that the official website table data export method uses the tabletools plug-in, which uses flash to export data, and does not support Chinese data. By searching the official API and information, I found the use of jquery and php export data method.
Javascript function to export data
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+' tbody tr:visible').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($('.csv-data').length) $('.csv-data').remove(); // open a p with a download link $('body').append('<p class="csv-data"><form enctype="multipart/form-data" method="post" action="/csv.php"><textarea class="form" name="csv">'+csv+'</textarea><input type="submit" class="submit" value="Download as file" /></form></p>'); } function strip_tags(html) { var tmp = document.createElement("p"); tmp.innerHTML = html; return tmp.textContent||tmp.innerText; }
The function supports exporting all data and the current page data
// export only what is visible right now (filters & paginationapplied) $('#export_visible').click(function(event) { var oTable; oTable= $('#spdata').dataTable(); event.preventDefault(); table2csv(oTable, 'visible', '#spdata'); }) // export all table data $('#export_all').click(function(event) { var oTable; oTable= $('#spdata').dataTable(); event.preventDefault(); table2csv(oTable, 'full', '#spdata'); })
where #spdata is the id of the table
Backend php export excel code
header("Content-Type: application/vnd.ms-execl"); header("Content-Disposition: attachment; filename=myExcel.csv"); header("Pragma: no-cache"); header("Expires: 0"); $buffer = $_POST['csv']; $buffer=str_replace(",",",\t",$buffer); $buffer=mb_convert_encoding($buffer,"GB2312","UTF-8"); echo $buffer;
The above is the detailed content of Detailed explanation of jquery export data to excel code example. For more information, please follow other related articles on the PHP Chinese website!