将 HTML 表格导出到 Excel JavaScript 函数添加选择文件名

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11084232/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-24 04:22:24  来源:igfitidea点击:

Export HTML table to Excel JavaScript function add select file name

javascriptasp.netexcelexportexport-to-excel

提问by VSP

I have the following function that exports an HTML to excel:

我有以下函数可以将 HTML 导出到 excel:

function generateexcel(tableid) {
  var table= document.getElementById(tableid);
  var html = table.outerHTML;
  window.open('data:application/vnd.ms-excel,' + encodeURIComponent(html));
}

The problem is that, i can't put a specific file name to save as so the user gets something like:

问题是,我无法保存特定的文件名,因此用户会得到如下内容:

Do you want to save %3Ctable%20id%3D%22tableRslts%22%20tabindex%3D%2235%22%20 file?

是否要保存 %3Ctable%20id%3D%22tableRslts%22%20tabindex%3D%2235%22%20 文件?

And the saved file is like:

保存的文件是这样的:

IytvT8Jo.xls.part.xls(at least in Firefox which is the target browser we will use)

IytvT8Jo.xls.part.xls(至少在我们将使用的目标浏览器 Firefox 中)

How would you fix this?

你会如何解决这个问题?

回答by David Mulder

There are two options which you could look into:

您可以查看两个选项:

  • Filesaver APIis new 'HTML5' functionality allowing /exactly/ this. There is just one small problem: the relevant part isn't supported yet in firefox. If you want to use this there is a nice wrapper library which makes this easier for you: filesaver.js
  • Downloadifyis a flash tool which is created for exactly this as well, you can find it here. ('Disadvantage': flash)
  • Filesaver API是新的“HTML5”功能,允许 /exactly/ 这个。只有一个小问题:Firefox 尚不支持相关部分。如果你想使用它,有一个很好的包装库可以让你更容易:filesaver.js
  • Downloadify是一个 Flash 工具,它也正是为此而创建的,您可以在此处找到它。('缺点':闪光)

回答by Siva Karthikeyan

I'm not sure if you have done this already. You might need to handle something like this below in your aspx page:

我不确定你是否已经这样做了。您可能需要在您的 aspx 页面中处理如下内容:

$(window).load(function(){
$( "#clickExcel" ).click(function() {  
var dtltbl = $('#dtltbl').html();    `enter code here`
window.open('data:application/vnd.ms-excel,' + $('#dtltbl').html());
});
});//]]>  

In the above script #dtltbl is the Table Id.

在上面的脚本中,#dtltbl 是表 ID。

The following code needs be there in your server side code, then your problem would be solved.

您的服务器端代码中需要有以下代码,然后您的问题就可以解决了。

           Response.AddHeader("Content-Disposition", "attachment;filename=myfilename.csv");