• 认真地记录技术中遇到的坑!

XLSX前端实现表格导出

JavaScript 悠悠 7个月前 (05-22) 468次浏览 0个评论

概述

js-xlsx是一个前端excel表格数据解析处理插件,兼容性非常好。

该插件github地址为:https://github.com/SheetJS/js-xlsx

Angular2中使用XLSX导出表格到本地

将表格数据,一个二维数组传入exportExcel方法的data即可,自动下载excel文件。

import * as XLSX from 'xlsx';

export class Excel {
    exportExcel(data: any[], filename = 'export.xlsx') {
        const ws_name = "SheetJS";

        // generate worksheet
        const ws: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(data);
        // generate workbook and add the worksheet
        const wb: XLSX.WorkBook = XLSX.utils.book_new();
        // add worksheet to workbook
        XLSX.utils.book_append_sheet(wb, ws, ws_name);
        // write workbook
        // XLSX.writeFile(wb, filename);

        // generate Blob
        const wbout: ArrayBuffer = XLSX.write(wb, {bookType: 'xlsx', type: 'array'});
        const blob: Blob = new Blob([wbout], {type: 'application/octet-stream'});

        // save file
        let link = document.createElement('a');
        link.href = URL.createObjectURL(blob);
        link.download = filename;
        link.click();
        setTimeout(function() {
            // 延时释放掉obj
            URL.revokeObjectURL(link.href);
            link.remove();
        }, 500);
    }
}

如果在nodejs端,还可以使用下面的更简单的方法:

/* generate worksheet */
const ws: XLSX.WorkSheet = XLSX.utils.aoa_to_sheet(this.data);

/* generate workbook and add the worksheet */
const wb: XLSX.WorkBook = XLSX.utils.book_new();
XLSX.utils.book_append_sheet(wb, ws, 'Sheet1');

/* save to file */
XLSX.writeFile(wb, 'SheetJS.xlsx');

一般JS中导出表格方法

导入JS:https://cdnjs.com/libraries/xlsx

<script lang="javascript" src="https://cdnjs.cloudflare.com/ajax/libs/xlsx/0.12.12/xlsx.full.min.js"></script>
<script>
function exportExcel(data) {
    const filename = 'redExcel.xlsx';
    const ws_name = "SheetJS";

    const worksheet = XLSX.utils.aoa_to_sheet(data);
    const workbook = XLSX.utils.book_new();
    XLSX.utils.book_append_sheet(workbook, worksheet, ws_name);
    // generate Blob
    const wbout = XLSX.write(workbook, {bookType: 'xlsx', type: 'array'});
    const blob = new Blob([wbout], {type: 'application/octet-stream'});
    // save file
    let link = document.createElement('a');
    link.href = URL.createObjectURL(blob);
    link.download = filename;
    link.click();
    setTimeout(function() {
        // 延时释放掉obj
        URL.revokeObjectURL(link.href);
        link.remove();
    }, 500);
}
</script>

转载请注明出处 XLSX前端实现表格导出
喜欢 (1)
发表我的评论
取消评论
表情 贴图 加粗 删除线 居中 斜体 签到

Hi,您需要填写昵称和邮箱!

  • 昵称 (必填)
  • 邮箱 (必填)
  • 网址