2016-04-28 17 views
2

我嘗試導出數據表中的HTML excel文件,但出口,現在,我不知道如何在savefiledialog彈出如何設置Excel中的文件名從HTML表

這裏我的代碼

設置文件名
$('#exportTable').click(function() { 

    var startDate = $('#startDate').val(); 
    var endDate = $('#endDate').val(); 
    searchReportWithDate(startDate, endDate); 

    setTimeout(function() { 
    var rowCount = $('#tblExportData >tbody >tr').length; 
    alert(rowCount); 
    if (rowCount > 0) 
    { 
     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" xmlns="http://www.w3.org/TR/REC-html40"><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]--><meta http-equiv="content-type" content="text/plain; charset=UTF-8"/></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) { 
     table = document.getElementById("tblExportData") 
     var ctx = {worksheet: name || 'Sheet1', table: table.innerHTML} 
     window.location.href = uri + base64(format(template, ctx)) 
     }() 
    } 
    }, 5000); 
}); 
+1

相關:http://stackoverflow.com/q/36914394/4928642 – Qwertiy

回答

2

刪除setTimeout,設置download attribite鏈接(點擊之前)並通過Blob流。

這是一個想法的例子。請務必檢查瀏覽器的每個部分。
https://jsfiddle.net/ppneeqjy/

document.querySelector("a").addEventListener('click', function (e) { 
 
    var data = new Uint8Array([0x89,0x50,0x4E,0x47,0x0D,0x0A,0x1A,0x0A,0x00,0x00,0x00,0x0D,0x49,0x48,0x44,0x52,0x00,0x00,0x00,0x08,0x00,0x00,0x00,0x08,0x01,0x03,0x00,0x00,0x00,0xFE,0xC1,0x2C,0xC8,0x00,0x00,0x00,0x06,0x50,0x4C,0x54,0x45,0xFF,0xFF,0xFF,0x00,0x00,0x00,0x55,0xC2,0xD3,0x7E,0x00,0x00,0x00,0x16,0x49,0x44,0x41,0x54,0x78,0x5E,0x63,0xF8,0xCF,0xD0,0xC8,0xB0,0x97,0x61,0x29,0x10,0xEE,0x05,0xB2,0xFE,0x03,0x00,0x2E,0x30,0x05,0xC5,0x31,0x03,0x9F,0xF7,0x00,0x00,0x00,0x00,0x49,0x45,0x4E,0x44,0xAE,0x42,0x60,0x82]); 
 
    var blob = new Blob([data], {type: 'image/png'}); 
 
    e.target.href = URL.createObjectURL(blob); 
 
});
<a href="#" download="smth.png">Click to download</a>

+0

我該如何設置「鏈接下載屬性(點擊之前)並傳遞Blob流」。在我的代碼中,請幫助我。 – kanabut

+0

謝謝你,我會試試這個。 – kanabut

0

,因爲它是在響應頭設置的附件文件名,我想你不能改變的,因爲你不能改變的響應頭在JavaScript

+0

有解決方案來解決這個問題? – kanabut

+1

有一個「newish」屬性,可以在a-tags上設置,它可以作爲下載,但支持有點稀疏:http://caniuse.com/#feat=download – andlrc

+0

您可以使用下載attrib由@andlrc提及)和函數[@Qwertiy提到](http://stackoverflow.com/questions/36914394/saving-file-created-from-browser-to-disk-cannot-use-new-file-on- Firefox瀏覽器) –

相關問題