本文介绍了有没有办法将HTML表导出到所有浏览器中的Excel?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用下面的代码,但它仅在Firefox中工作。
它也不允许自定义导出的文件名。它需要一个随机文件名。
I used below code for that but its works only in Firefox.It also not allow customize exported file name. It takes a random file name.
var tableToExcel = (function () {
var uri = 'data:application/vnd.ms-excel;base64,'
, template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel" ><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>'
, base64 = function (s) { return window.btoa(unescape(encodeURIComponent(s))) }
, format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) }
return function (table, name, filename) {
var OriginalHTML = $('#' + table + '').html();
if (!table.nodeType) {
table = document.getElementById(table);
$(table).find(".EditColumns").remove();
}
var ctx = { worksheet: name || 'Worksheet', table: table.innerHTML }
$(table).html(OriginalHTML);
//window.location.href = uri + base64(format(template, ctx))
document.getElementById("aExportTable").href = uri + base64(format(template, ctx));
document.getElementById("aExportTable").download = filename;
document.getElementById("aExportTable").click();
HighlightSelectedRow();
}
})();
推荐答案
尝试一个。应该在IE10 +,Chrome / Safari和Fx中工作
Try a blob. Should work in IE10+, Chrome/Safari and Fx
window.URL = window.URL || window.webkitURL;
var blob = new Blob([format(template, ctx)]); // format is part of OP's code
var blobURL = window.URL.createObjectURL(blob);
if (blobURL) {
$("<a/>")
.attr("href", blobURL)
.attr("download", fileName)
.text("Download "+fileName+" for import")
.appendTo('#downloadLink');
}
else {
$("#downloadLink").html("Please cut and paste from the table below");
}
这篇关于有没有办法将HTML表导出到所有浏览器中的Excel?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!