将HTML表格导出到Excel

前端之家收集整理的这篇文章主要介绍了将HTML表格导出到Excel前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
用户点击“导出”按钮时,我需要将页面中的html表导出到Excel。现在,我在Firefox中找到了一个解决方案。

Export dynamic html table to excel in javascript in firefox browser

现在,它不会处理像ö,ü,ö这样常用的特殊字符,我们在这里使用的语言很常见,所以我想询问是否有人知道如何成功导出它们,没有问题?

这是我的代码

function tabletoExcel(table,name) {
    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]; }); };
        if (!table.nodeType) table = document.getElementById(table);
        var ctx = { worksheet: name || 'Worksheet',table: table.innerHTML };
        window.location.href = uri + base64(format(template,ctx));

}

解决方法

如果添加
<Meta http-equiv="content-type" content="text/plain; charset=UTF-8"/>

文件的头上,它将按预期开始工作:

<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,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>

Updated Fiddle Here.

原文链接:https://www.f2er.com/html/233284.html

猜你在找的HTML相关文章