使用javascript导出时excel工作表中的上标

Superscript in excel sheet while exporting using javascript

本文关键字:上标 工作 excel javascript 使用      更新时间:2023-09-26

我正在使用以下Javascript代码从HTML页面导出一个表:

<script>
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))
 }
})()
</script>
<body>
<table id="maintable">
some table content
</table>
<input type="button" onClick=tableToExcel(maintable,"tablename") />
</body>

此代码将表格转换为excel表格。

但是上标字符不会向上移动,而是保持原样。

示例:X2在excel中变为X2。

我也试过unicode''u00B2,但它不起作用。

是否可以将上标字符导出到excel?如果是,我该如何做到这一点。

提前谢谢。

[编辑]如果我使用unicode²;或±;或²

原来上面的脚本无法正确转换unicode。对我来说,最好的解决方案是使用html标签sup,如下所示:

<tr>
    <td>X<sup>2</sup></td>
</tr>

希望这能有所帮助。