前端实现excel导出

更新日期: 2020-12-22阅读: 2.1k标签: excel

1.引入所需的依赖文件

https://github.com/SheetJS/sheetjs
https://github.com/eligrey/FileSaver.js

<script src="https://cdn.bootcss.com/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
<script lang="javascript" src="dist/xlsx.full.min.js"></script>


2.s2ab函数

function s2ab(s) {
    const buf = new ArrayBuffer(s.length);
    const view = new Uint8Array(buf);
    for (let i = 0; i !== s.length; ++i) {
        view[i] = s.charCodeAt(i) & 0xFF;
    };
    return buf;
}


3.所需要的数据结构

[
    ["列A", "列B"], // 这将作为excel文件的标题
    [1,2]
]


4.一个例子

let data = [
    ["列A", "列B"],
    [3,4]
];

let wopts = { bookType:'xlsx', type:'binary' };
let fileName = "bill.xlsx";

const ws = XLSX.utils.aoa_to_sheet(data);
const wb = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

const wbout = XLSX.write(wb, wopts);
saveAs(new Blob([s2ab(wbout)]), fileName); // 保存为文件

链接: https://fly63.com/article/detial/9978

内容以共享、参考、研究为目的,不存在任何商业目的。其版权属原作者所有,如有侵权或违规,请与小编联系!情况属实本人将予以删除!