網頁中的實現方式

  1. 引入所需的依賴檔案
<script src="https://cdn.bootcss.com/FileSaver.js/2014-11-29/FileSaver.min.js"></script>
<script src="https://cdn.bootcss.com/xlsx/0.11.3/xlsx.full.min.js"></script>
  1. 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;
}
  1. 所需要的資料結構
[
    ["列A", "列B"], // 這將作為excel檔案的標題
    [1,2]
]
  1. 一個例子
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); // 儲存為檔案

混合開發中的實現方式

ionic框架為例。
1. 安裝並引入依賴

import { File } from '@ionic-native/file';
import * as XLSX from 'xlsx';

這裡不再使用FileSaver.js,轉而使用@ionic-native/file以將檔案儲存到移動裝置中。

  1. 一個例子
import { File } from '@ionic-native/file';
import * as XLSX from 'xlsx';


constructor(private file: File) {

}

/**
 * 將資料匯出為.xlsx檔案
 * 依賴:File、XLSX
 */
exportBill():void {
    function s2ab(s: string): ArrayBuffer {
        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;
    }

    let data = [[1,2],[3,4]];
    let wopts: XLSX.WritingOptions = { bookType:'xlsx', type:'binary' };
    let fileName: string = "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);
    console.log(wbout);

    /**
     * 儲存到檔案
     */
    let blob = new Blob([s2ab(wbout)]);
    let pathFile = '';
    if (this.plarform.is('ios')) {
        pathFile = this.file.documentsDirectory;
    }
    else {
        pathFile = this.file.externalDataDirectory;
    }

    this.file.writeFile(pathFile, 'bill.xlsx', blob, { replace: true })
        .then((success) => {
            console.log(success);
        }, (err) => {
            alert(err);
        });
}