Export HTML table to Excel JavaScript function add select file name

☆樱花仙子☆ 提交于 2020-01-01 04:19:11

问题


I have the following function that exports an HTML to 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?

And the saved file is like:

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

How would you fix this?


回答1:


There are two options which you could look into:

  • Filesaver API is 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
  • Downloadify is a flash tool which is created for exactly this as well, you can find it here. ('Disadvantage': flash)



回答2:


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

$(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.

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");


来源:https://stackoverflow.com/questions/11084232/export-html-table-to-excel-javascript-function-add-select-file-name

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!