我的@sampopes答案版本
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;
}
}
需要iframe
<iframe id="myIframe" style="opacity: 0; width: 100%; height: 0px;" seamless="seamless"></iframe>
用法
$("#btnExportToExcel").click(function () {
exportToExcel(this, '#mytable');
});