[英]How Do I Export Data From HTML Webpage Using Javascript To Microsoft Excel Keeping The GridLines Turned On?
我整個下午一直在研究,並嘗試使用我在互聯網和 Stack OverFlow 上找到的各種解決方案,以嘗試在我從 HTML 網頁導出數據時保持網格線打開,但無濟於事。 我真的很想避免使用插件,而我認為這種簡單的東西不應該需要。 我真的很震驚,事實證明這和它一樣具有挑戰性。 無論如何......我找到了這個代碼......
function exportTableToExcel(tableID, filename = ''){
var downloadLink;
var dataType = 'application/vnd.ms-excel';
var tableSelect = document.getElementById(tableID);
var tableHTML = tableSelect.outerHTML.replace(/ /g, '%20');
// Specify file name
filename = filename?filename+'.xls':'excel_data.xls';
// Create download link element
downloadLink = document.createElement("a");
document.body.appendChild(downloadLink);
if(navigator.msSaveOrOpenBlob){
var blob = new Blob(['\ufeff', tableHTML], {
type: dataType
});
navigator.msSaveOrOpenBlob( blob, filename);
}else{
// Create a link to the file
downloadLink.href = 'data:' + dataType + ', ' + tableHTML;
// Setting the file name
downloadLink.download = filename;
//triggering the function
downloadLink.click();
}
}
再加上這個HTML.....
<table id="tblData" class="table10">
<tr>
<th class="title36">Description</th>
</tr>
</table>
<button onclick="exportTableToExcel('tblData')"</button>
這一切都很好! 除了當我打開文件時,網格線消失了,用戶每次都必須轉到視圖選項卡並重新打開網格線。 是否有我可以在某處更改的設置允許這樣做?
這個 SO 中的第二個例子有效......但我有一個問題,我需要使用一個按鈕而不是一個輸入按鈕......為了樣式目的......然后這樣做是因為解決方案被寫成一個 var而不是一個函數....我在解決這個問題時遇到了麻煩。 所以我知道我正在嘗試做的事情是可能的......我只是無法弄清楚如何在沒有插件的情況下將其作為 Javascript 來執行。 我對 Javascript 還很陌生,所以提前感謝您的指點……也許我可以如何將第二個解決方案重寫為函數?
這是我發現有效的代碼......
<script type="text/javascript">
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" 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) {
if (!table.nodeType) table = document.getElementById(table)
var ctx = {worksheet: name || 'Worksheet', table: table.innerHTML}
window.location.href = uri + base64(format(template, ctx))
}
})()
</script>
但是我需要重寫它,以便我可以像上面代碼開頭引用的第一個函數一樣調用它。 再次感謝您的任何指點或想法。
經過更多研究,我意識到第二段代碼就是答案。 我只需要按如下方式更新我的 HTML 按鈕參考...
<button type="button" onclick="tableToExcel('tblData',)" class="class"><div class="class1"><h3 class="class2">Export To Excel</h3></div></button>
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.