全部 / 前端 / 技术 · 2022年10月21日 0

JSON 导出为 Excel

广告位招租 (vx: ghostcode, 备注:网站广告)

JSON 数据导出 Excel 文件需要借助 SheetJS 这个开源库。

HTML 表格导出为 Excel 文件

<!-- 文件中引入脚本-->
<script src="https://cdn.sheetjs.com/xlsx-latest/package/dist/xlsx.full.min.js"></script>

<!--表格-->
<table id="TableToExport">

<!--导出按钮-->
<button id="sheetjsexport"><b>Export as XLSX</b></button>


<script>
document.getElementById("sheetjsexport").addEventListener('click', function() {
  /* Create worksheet from HTML DOM TABLE */
  var wb = XLSX.utils.table_to_book(document.getElementById("TableToExport"));
  /* Export to file (start a download) */
  XLSX.writeFile(wb, "SheetJSTable.xlsx");
});
</script>

注意:

  1. 选择的元素必须为 Table 否则会报错。

  1. 如果是 UI 库生成的表格,要特别注意实际的 HMLT 并不是一个 Table:

所以在导出的时候,可能只有标题没有数据:

解决方案是:拼接两个表格。

const exportTableWrap = document.querySelector(".export-table");
const tables = exportTableWrap.querySelectorAll('.ant-table-fixed')
const ws = XLSX.utils.table_to_sheet(tables[0]);

XLSX.utils.sheet_add_dom(ws,tables[1],{
origin:-1,
})

const wb = XLSX.utils.book_new()
XLSX.utils.book_append_sheet(wb,ws)
XLSX.writeFile(wb, "统计分析.xlsx")

参考:https://docs.sheetjs.com/docs/api/utilities#html-table-input

下载的表格正确,但是日期那一列出问题了。由于太窄导致日期不显示:

解决:设置列宽。

效果如下:

参考:

  1. https://docs.sheetjs.com/docs/csf/features/#row-and-column-properties
  2. https://docs.sheetjs.com/docs/getting-started/example#clean-up-workbook
  3. https://blog.csdn.net/a843334549/article/details/114651578
  4. https://www.jianshu.com/p/e2cd2cb28ba9

JSON 数据导出 Excel 文件

参考:

  1. https://docs.sheetjs.com/docs/getting-started/example
  2. https://blog.csdn.net/weixin_41897680/article/details/123109969