Saya memiliki tabel HTML dalam template kecepatan. Saya ingin mengekspor data tabel html ke excel baik menggunakan java script atau jquery, comatibale dengan semua browser. Saya menggunakan skrip di bawah ini
<script type="text/javascript">
function ExportToExcel(mytblId){
var htmltable= document.getElementById('my-table-id');
var html = htmltable.outerHTML;
window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html));
}
</script>
Skrip ini berfungsi dengan baik di Mozilla Firefox , ini muncul dengan kotak dialog excel dan meminta opsi buka atau simpan. Tetapi ketika saya menguji skrip yang sama di browser Chrome itu tidak berfungsi seperti yang diharapkan, ketika tombol diklik tidak ada pop-up untuk excel. Data diunduh dalam file dengan "tipe file: file", tanpa ekstensi seperti .xls Tidak ada kesalahan dalam konsol chrome.
Contoh jsfiddle:
http://jsfiddle.net/insin/cmewv/
Ini berfungsi dengan baik di mozilla tetapi tidak di chrome.
Kasus Uji browser Chrome:
Gambar Pertama: Saya mengklik tombol Export to excel
dan hasil:
sumber
Jawaban:
Skrip ekspor Excel berfungsi di IE7 +, Firefox dan Chrome.
function fnExcelReport() { var tab_text="<table border='2px'><tr bgcolor='#87AFC6'>"; var textRange; var j=0; tab = document.getElementById('headerTable'); // id of table for(j = 0 ; j < tab.rows.length ; j++) { tab_text=tab_text+tab.rows[j].innerHTML+"</tr>"; //tab_text=tab_text+"</tr>"; } tab_text=tab_text+"</table>"; tab_text= tab_text.replace(/<A[^>]*>|<\/A>/g, "");//remove if u want links in your table tab_text= tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table tab_text= tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params var ua = window.navigator.userAgent; var msie = ua.indexOf("MSIE "); if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer { txtArea1.document.open("txt/html","replace"); txtArea1.document.write(tab_text); txtArea1.document.close(); txtArea1.focus(); sa=txtArea1.document.execCommand("SaveAs",true,"Say Thanks to Sumit.xls"); } else //other browser not tested on IE 11 sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text)); return (sa); }
Buat saja iframe kosong:
<iframe id="txtArea1" style="display:none"></iframe>
Panggil fungsi ini di:
<button id="btnExport" onclick="fnExcelReport();"> EXPORT </button>
sumber
Plugin Datatable menyelesaikan tujuan terbaik dan memungkinkan kita mengekspor data tabel HTML ke Excel, PDF, TEXT. mudah dikonfigurasi.
Silakan temukan contoh lengkap di tautan referensi yang dapat ditautkan di bawah ini:
https://datatables.net/extensions/buttons/examples/html5/simple.html
(tangkapan layar dari situs referensi data)
sumber
Ini bisa membantu
function exportToExcel(){ var htmls = ""; var uri = 'data:application/vnd.ms-excel;base64,'; var 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>'; var base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }; var format = function(s, c) { return s.replace(/{(\w+)}/g, function(m, p) { return c[p]; }) }; htmls = "YOUR HTML AS TABLE" var ctx = { worksheet : 'Worksheet', table : htmls } var link = document.createElement("a"); link.download = "export.xls"; link.href = uri + base64(format(template, ctx)); link.click(); }
sumber
http://wsnippets.com/export-html-table-data-excel-sheet-using-jquery/ coba tautan ini mungkin dapat menyelesaikan masalah Anda
sumber
Daripada menggunakan
window.open
Anda dapat menggunakan link denganonclick
acara tersebut.Dan Anda dapat meletakkan tabel html ke dalam uri dan mengatur nama file yang akan diunduh.
Demo langsung:
function exportF(elem) { var table = document.getElementById("table"); var html = table.outerHTML; var url = 'data:application/vnd.ms-excel,' + escape(html); // Set your html table into url elem.setAttribute("href", url); elem.setAttribute("download", "export.xls"); // Choose the file name return false; }
<table id="table" border="1"> <tr> <td> Foo </td> <td> Bar </td> </tr> </table> <a id="downloadLink" onclick="exportF(this)">Export to excel</a>
sumber
TableExport - Pustaka sederhana dan mudah diterapkan untuk mengekspor tabel HTML ke file xlsx, xls, csv, dan txt.
Untuk menggunakan perpustakaan ini, panggil
TableExport
konstruktor:new TableExport(document.getElementsByTagName("table")); // OR simply TableExport(document.getElementsByTagName("table")); // OR using jQuery $("table").tableExport();
Properti tambahan dapat diteruskan untuk menyesuaikan tampilan dan nuansa tabel, tombol, dan data yang diekspor. Lihat di sini info lebih lanjut
sumber
Penggabungan saya dari contoh-contoh ini:
https://www.codexworld.com/export-html-table-data-to-excel-using-javascript https://bl.ocks.org/Flyer53/1de5a78de9c89850999c
function exportTableToExcel(tableId, filename) { let dataType = 'application/vnd.ms-excel'; let extension = '.xls'; let base64 = function(s) { return window.btoa(unescape(encodeURIComponent(s))) }; let 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>'; let render = function(template, content) { return template.replace(/{(\w+)}/g, function(m, p) { return content[p]; }); }; let tableElement = document.getElementById(tableId); let tableExcel = render(template, { worksheet: filename, table: tableElement.innerHTML }); filename = filename + extension; if (navigator.msSaveOrOpenBlob) { let blob = new Blob( [ '\ufeff', tableExcel ], { type: dataType } ); navigator.msSaveOrOpenBlob(blob, filename); } else { let downloadLink = document.createElement("a"); document.body.appendChild(downloadLink); downloadLink.href = 'data:' + dataType + ';base64,' + base64(tableExcel); downloadLink.download = filename; downloadLink.click(); } }
sumber
Anda dapat menggunakan perpustakaan seperti ShieldUI untuk melakukan itu.
Ini mendukung ekspor ke format Excel yang banyak digunakan XML dan XLSX.
Detail lebih lanjut di sini: http://demos.shieldui.com/web/grid-general/export-to-excel
sumber
Mengenai contoh jawaban dari 6 Juni '14 pukul 11:59:
Saya telah menyisipkan gaya css dengan ukuran font 20px untuk menampilkan data excel yang lebih besar. Dalam kode sampel,
<tr>
tag utama hilang, jadi saya pertama-tama mengeluarkan informasi utama dan daripada baris tabel lainnya dalam satu lingkaran.function fnExcelReport() { var tab_text = '<table border="1px" style="font-size:20px" ">'; var textRange; var j = 0; var tab = document.getElementById('DataTableId'); // id of table var lines = tab.rows.length; // the first headline of the table if (lines > 0) { tab_text = tab_text + '<tr bgcolor="#DFDFDF">' + tab.rows[0].innerHTML + '</tr>'; } // table data lines, loop starting from 1 for (j = 1 ; j < lines; j++) { tab_text = tab_text + "<tr>" + tab.rows[j].innerHTML + "</tr>"; } tab_text = tab_text + "</table>"; tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, ""); //remove if u want links in your table tab_text = tab_text.replace(/<img[^>]*>/gi,""); // remove if u want images in your table tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); // reomves input params // console.log(tab_text); // aktivate so see the result (press F12 in browser) var ua = window.navigator.userAgent; var msie = ua.indexOf("MSIE "); // if Internet Explorer if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) { txtArea1.document.open("txt/html","replace"); txtArea1.document.write(tab_text); txtArea1.document.close(); txtArea1.focus(); sa = txtArea1.document.execCommand("SaveAs", true, "DataTableExport.xls"); } else // other browser not tested on IE 11 sa = window.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text)); return (sa); }
sumber
tab.rows[j].cells[13]
, bantuan Anda sangat dihargaiwindow.open('data:application/vnd.ms-excel,' + encodeURIComponent(tab_text));
enconding sangat penting.function exportToExcel() { var tab_text = "<tr bgcolor='#87AFC6'>"; var textRange; var j = 0, rows = ''; tab = document.getElementById('student-detail'); tab_text = tab_text + tab.rows[0].innerHTML + "</tr>"; var tableData = $('#student-detail').DataTable().rows().data(); for (var i = 0; i < tableData.length; i++) { rows += '<tr>' + '<td>' + tableData[i].value1 + '</td>' + '<td>' + tableData[i].value2 + '</td>' + '<td>' + tableData[i].value3 + '</td>' + '<td>' + tableData[i].value4 + '</td>' + '<td>' + tableData[i].value5 + '</td>' + '<td>' + tableData[i].value6 + '</td>' + '<td>' + tableData[i].value7 + '</td>' + '<td>' + tableData[i].value8 + '</td>' + '<td>' + tableData[i].value9 + '</td>' + '<td>' + tableData[i].value10 + '</td>' + '</tr>'; } tab_text += rows; var data_type = 'data:application/vnd.ms-excel;base64,', 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 border="2px">{table}</table></body></html>', base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }, format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) } var ctx = { worksheet: "Sheet 1" || 'Worksheet', table: tab_text } document.getElementById("dlink").href = data_type + base64(format(template, ctx)); document.getElementById("dlink").download = "StudentDetails.xls"; document.getElementById("dlink").traget = "_blank"; document.getElementById("dlink").click(); }
Di sini Nilai 1 sampai 10 adalah nama kolom yang Anda dapatkan
sumber
Anda dapat menggunakan tableToExcel.js untuk mengekspor tabel dalam file excel.
Ini bekerja dengan cara berikut:
1). Sertakan CDN ini dalam proyek / file Anda
<script src="https://cdn.jsdelivr.net/gh/linways/[email protected]/dist/tableToExcel.js"></script>
2). Baik Menggunakan JavaScript:
<button id="btnExport" onclick="exportReportToExcel(this)">EXPORT REPORT</button> function exportReportToExcel() { let table = document.getElementsByTagName("table"); // you can use document.getElementById('tableId') as well by providing id to the table tag TableToExcel.convert(table[0], { // html code may contain multiple tables so here we are refering to 1st table tag name: `export.xlsx`, // fileName you could use any name sheet: { name: 'Sheet 1' // sheetName } }); }
3). Atau dengan Menggunakan Jquery
<button id="btnExport">EXPORT REPORT</button> $(document).ready(function(){ $("#btnExport").click(function() { let table = document.getElementsByTagName("table"); TableToExcel.convert(table[0], { // html code may contain multiple tables so here we are refering to 1st table tag name: `export.xlsx`, // fileName you could use any name sheet: { name: 'Sheet 1' // sheetName } }); }); });
Anda dapat merujuk ke tautan github ini untuk informasi lainnya
https://github.com/linways/table-to-excel/tree/master
atau untuk merujuk contoh langsung kunjungi tautan berikut
https://codepen.io/rohithb/pen/YdjVbb
Semoga ini bisa membantu seseorang :-)
sumber
Jawaban @sampopes versi saya
function exportToExcel(that, id, hasHeader, removeLinks, removeImages, removeInputParams) { if (that == null || typeof that === 'undefined') { console.log('Sender is required'); return false; } if (!(that instanceof HTMLAnchorElement)) { console.log('Sender must be an anchor element'); return false; } if (id == null || typeof id === 'undefined') { console.log('Table id is required'); return false; } if (hasHeader == null || typeof hasHeader === 'undefined') { hasHeader = true; } if (removeLinks == null || typeof removeLinks === 'undefined') { removeLinks = true; } if (removeImages == null || typeof removeImages === 'undefined') { removeImages = false; } if (removeInputParams == null || typeof removeInputParams === 'undefined') { removeInputParams = true; } var tab_text = "<table border='2px'>"; var textRange; tab = $(id).get(0); if (tab == null || typeof tab === 'undefined') { console.log('Table not found'); return; } var j = 0; if (hasHeader && tab.rows.length > 0) { var row = tab.rows[0]; tab_text += "<tr bgcolor='#87AFC6'>"; for (var l = 0; l < row.cells.length; l++) { if ($(tab.rows[0].cells[l]).is(':visible')) {//export visible cols only tab_text += "<td>" + row.cells[l].innerHTML + "</td>"; } } tab_text += "</tr>"; j++; } for (; j < tab.rows.length; j++) { var row = tab.rows[j]; tab_text += "<tr>"; for (var l = 0; l < row.cells.length; l++) { if ($(tab.rows[j].cells[l]).is(':visible')) {//export visible cols only tab_text += "<td>" + row.cells[l].innerHTML + "</td>"; } } tab_text += "</tr>"; } tab_text = tab_text + "</table>"; if (removeLinks) tab_text = tab_text.replace(/<A[^>]*>|<\/A>/g, ""); if (removeImages) tab_text = tab_text.replace(/<img[^>]*>/gi, ""); if (removeInputParams) tab_text = tab_text.replace(/<input[^>]*>|<\/input>/gi, ""); var ua = window.navigator.userAgent; var msie = ua.indexOf("MSIE "); if (msie > 0 || !!navigator.userAgent.match(/Trident.*rv\:11\./)) // If Internet Explorer { myIframe.document.open("txt/html", "replace"); myIframe.document.write(tab_text); myIframe.document.close(); myIframe.focus(); sa = myIframe.document.execCommand("SaveAs", true, document.title + ".xls"); return true; } else { //other browser tested on IE 11 var result = "data:application/vnd.ms-excel," + encodeURIComponent(tab_text); that.href = result; that.download = document.title + ".xls"; return true; } }
Membutuhkan iframe
<iframe id="myIframe" style="opacity: 0; width: 100%; height: 0px;" seamless="seamless"></iframe>
Pemakaian
$("#btnExportToExcel").click(function () { exportToExcel(this, '#mytable'); });
sumber