gpt4 book ai didi

javascript - div 中的 Html 表格导出到 excel

转载 作者:行者123 更新时间:2023-11-30 11:45:25 26 4
gpt4 key购买 nike

  <script type="text/javascript">
$(document).ready(function () {
//getting values of current time for generating the file name
$(".toExcelButton").click(function(){
var dt = new Date();
var day = dt.getDate();
var month = dt.getMonth() + 1;
var year = dt.getFullYear();
var hour = dt.getHours();
var mins = dt.getMinutes();
var postfix = day + "." + month + "." + year + "_" + hour + "." + mins;
//creating a temporary HTML link element (they support setting file names)
var a = document.createElement('a');
//getting data from our div that contains the HTML table
var data_type = 'data:application/vnd.ms-excel';
var table_div = document.getElementById('dvData');
var table_html = table_div.outerHTML.replace(/ /g, '%20');
a.href = data_type + ', ' + table_html;
//setting the file name
a.download = 'exported_table_' + postfix + '.xls';
//triggering the function
a.click();
//just in case, prevent default behaviour
e.preventDefault();
})
});
</script>

需要将div 表导出到excel。上面的代码在 Chrome 中运行良好,但在 IE 中无法运行。谁能帮我解决这个问题。

最佳答案

在 IE 中,需要将动态创建的 anchor 标记添加到 DOM 以执行其点击事件。此外,IE 不支持下载属性:

Download attribute on A tag not working in IE

编辑:

最近我发布了很多解决这个问题的答案,这里有两个:

image does not download with it's own extension

JS Base64 string to downloadable pdf - Edge

基本上你必须在 IE 中使用 msSaveOrOpenBlob():

var tF = 'Whatever.xls';
var tB = new Blob(..);

if(window.top.navigator.msSaveOrOpenBlob){
//Store Blob in IE
window.top.navigator.msSaveOrOpenBlob(tB, tF)
}
else{
//Store Blob in others
var tA = document.body.appendChild(document.createElement('a'));
tA.href = URL.createObjectURL(tB);
tA.download = tF;
tA.style.display = 'none';
tA.click();
tA.parentNode.removeChild(tA)
}

在上面的例子中:

var tT = new XMLSerializer().serializeToString(document.querySelector('table')); //Serialised table
var tF = 'Whatever.xls'; //Filename
var tB = new Blob([tT]); //Blob

if(window.top.navigator.msSaveOrOpenBlob){
//Store Blob in IE
window.top.navigator.msSaveOrOpenBlob(tB, tF)
}
else{
//Store Blob in others
var tA = document.body.appendChild(document.createElement('a'));
tA.href = URL.createObjectURL(tB);
tA.download = tF;
tA.style.display = 'none';
tA.click();
tA.parentNode.removeChild(tA)
}

https://jsfiddle.net/23ao1v0s/1/

关于javascript - div 中的 Html 表格导出到 excel,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41159530/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com