使用FileSaver、js-xlsx实现excel导出

需要将页面上的表格内容导出成excel格式。
使用了FileSaver、js-xlsx的前端插件。

                    files: [
                        vendor_path('file-saver/FileSaver.min.js'),
                        vendor_path('js-xlsx/dist/xlsx.core.min.js'),
                    ]

FileSaver、js-xlsx的github,支持的版本类型,和使用方法。
js-xlsx:

    datenum = (v, date1904) ->
        if date1904
            v += 1462
        epoch = Date.parse(v)
        return (epoch - new Date(Date.UTC(1899, 11, 30))) / (24 * 60 * 60 * 1000)


    sheetFromArrayOfArrays = (data) ->
        ws =
            # 设置每一列的宽度(12个字符)
            '!cols': ({wch: 12} for i in _.range(data[0].length))
        range =
            s:
                c: 10000000
                r: 10000000
            e:
                c: 0
                r: 0
        R = 0
        while R != data.length
            C = 0
            while C != data[R].length
                if range.s.r > R
                    range.s.r = R
                if range.s.c > C
                    range.s.c = C
                if range.e.r < R
                    range.e.r = R
                if range.e.c < C
                    range.e.c = C

                cell = v: data[R][C]
                if cell.v == null
                    ++C
                    continue

                cell_ref = XLSX.utils.encode_cell(
                    c: C
                    r: R)

                if typeof cell.v == 'number'
                    cell.t = 'n'
                else if typeof cell.v == 'boolean'
                    cell.t = 'b'
                else if cell.v instanceof Date
                    cell.t = 'n'
                    cell.z = XLSX.SSF._table[14]
                    cell.v = datenum(cell.v)
                else
                    cell.t = 's'
                ws[cell_ref] = cell
                ++C
            ++R
        if range.s.c < 10000000
            ws['!ref'] = XLSX.utils.encode_range(range)
        return ws


    s2ab = (s) ->
        buf = new ArrayBuffer(s.length)
        view = new Uint8Array(buf)

        for i in _.range(s.length)
            view[i] = s.charCodeAt(i) & 0xFF

        return buf

FileSaver:

            filename = "ge.xlsx"
            wb =
                SheetNames: []
                Sheets: {}

            ws = sheetFromArrayOfArrays(data)
            sheet_name = "ge"
            wb.SheetNames.push sheet_name
            wb.Sheets[sheet_name] = ws

            if wb.SheetNames.length == 0
                return showErr()

            wbout = XLSX.write(wb, {bookType: 'xlsx', bookSST: true, type: 'binary'})
            saveAs(new Blob([s2ab(wbout)], {type: "application/octet-stream"}), filename)


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

你可能感兴趣的:(使用FileSaver、js-xlsx实现excel导出)