使用javascript导出时excel sheet中的上标

时间:2014-09-26 08:41:36

标签: javascript html excel export

我正在使用以下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表格。

但上标字符不会向上移动但保持不变。

示例:X 2 在excel中变为X2。

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

是否可以将上标字符导出为ex​​cel? 如果是的话,我怎样才能做到这一点。

提前致谢。

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

,我的输出就像X²

1 个答案:

答案 0 :(得分:2)

事实证明,上述脚本无法正确转换unicode。 对我有用的最佳解决方案是使用html标签,如下所示:

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

希望这有帮助。