9

网页中的实现方式

1.引入所需的依赖文件
https://github.com/SheetJS/sh...
https://github.com/eligrey/Fi...

<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); // 保存为文件

小谷xg
2.3k 声望297 粉丝

明月清风自在怀,任重道远常心态。坎坷人生从容走,否极自有安泰来。