gpt4 book ai didi

javascript - 在单独的工作表中将 HTML 表格导出到 Excel (.xls)

转载 作者:技术小花猫 更新时间:2023-10-29 12:43:22 25 4
gpt4 key购买 nike

我有一个包含表格 View 的简单 HTML 页面(由外部应用程序生成)。我试图从页面上刮下表格并将它们放入 Excel 工作簿中。我已经设法通过使用可用的方法将整个 HTML 内容放入工作簿中 here .

相关问题的代码:

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]--></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))
}
})()

但是该方法不支持多个电子表格。我需要的是每个 HTML 表格都在同一个 Excel 工作簿中自己的 SpreadSheet 中。是这样的: enter image description here

我曾尝试使用两个电子表格创建示例 Excel 文档,然后通过查看 .html 格式的导出文件对其进行逆向工程。不幸的是,我不明白如何重新创建工作簿和工作表之间的连接。

据我所知,format() 函数实现了工作表数据和 Excel 模板的“神奇”组合。这个函数对我来说看起来很神秘,所以我不知道如何修改它。

作为最终游戏,我需要的是能够调用类似的东西。tableToExcel(document.getElementsByTagName('table'), '工作簿名称');

如果这完全可能,您有什么想法吗?如果可以,如何实现它?

最佳答案

查看此博文:http://www.kubilayerdogan.net/?p=218

 $(document).ready(function() {
$("#btnExport").click(function(e) {
//getting values of current time for generating the file name
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();
});
});

您可以在 jsfiddle 中看到它的运行情况:http://jsfiddle.net/kublaios/8ZQN4/1/

关于javascript - 在单独的工作表中将 HTML 表格导出到 Excel (.xls),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18234448/

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