1. 程式人生 > >javascript--利用js-xlsx實現Excel表格的匯入匯出

javascript--利用js-xlsx實現Excel表格的匯入匯出

<button onclick="downloadExl(jsono)">匯出</button>
<script src="js-xlsx/xlsx.full.min.js"></script>
<!--呼叫FileSaver saveAs函式可以實現檔案下載-->
<!--<script src="http://sheetjs.com/demos/Blob.js"></script>
<script src="http://sheetjs.com/demos/FileSaver.js"></script>-->
<script>
    //如果使用 FileSaver.js 就不要同時使用以下函式
    function saveAs(obj, fileName) {//當然可以自定義簡單的下載檔案實現方式 
        var tmpa = document.createElement("a");
        tmpa.download = fileName || "下載";
        tmpa.href = URL.createObjectURL(obj); //繫結a標籤
        tmpa.click(); //模擬點選實現下載
        setTimeout(function () { //延時釋放
            URL.revokeObjectURL(obj); //用URL.revokeObjectURL()來釋放這個object URL
        }, 100);
    }
    var jsono = [{ //測試資料
        "保質期臨期預警(天)": "adventLifecycle",
        "商品標題": "title",
        "建議零售價": "defaultPrice",
        "高(cm)": "height",
        "商品描述": "Description",
        "保質期禁售(天)": "lockupLifecycle",
        "商品名稱": "skuName",
        "商品簡介": "brief",
        "寬(cm)": "width",
        "阿達": "asdz",
        "貨號": "goodsNo",
        "商品條碼": "skuNo",
        "商品品牌": "brand",
        "淨容積(cm^3)": "netVolume",
        "是否保質期管理": "isShelfLifeMgmt",
        "是否串號管理": "isSNMgmt",
        "商品顏色": "color",
        "尺碼": "size",
        "是否批次管理": "isBatchMgmt",
        "商品編號": "skuCode",
        "商品簡稱": "shortName",
        "毛重(g)": "grossWeight",
        "長(cm)": "length",
        "英文名稱": "englishName",
        "淨重(g)": "netWeight",
        "商品分類": "categoryId",
        "這裡超過了": 1111.0,
        "保質期(天)": "expDate"
    }];
    const wopts = { bookType: 'xlsx', bookSST: false, type: 'binary' };//這裡的資料是用來定義匯出的格式型別
    // const wopts = { bookType: 'csv', bookSST: false, type: 'binary' };//ods格式
    // const wopts = { bookType: 'ods', bookSST: false, type: 'binary' };//ods格式
    // const wopts = { bookType: 'xlsb', bookSST: false, type: 'binary' };//xlsb格式
    // const wopts = { bookType: 'fods', bookSST: false, type: 'binary' };//fods格式
    // const wopts = { bookType: 'biff2', bookSST: false, type: 'binary' };//xls格式

    function downloadExl(data, type) {
        const wb = { SheetNames: ['Sheet1'], Sheets: {}, Props: {} };
        wb.Sheets['Sheet1'] = XLSX.utils.json_to_sheet(data);//通過json_to_sheet轉成單頁(Sheet)資料
        saveAs(new Blob([s2ab(XLSX.write(wb, wopts))], { type: "application/octet-stream" }), "這裡是下載的檔名" + '.' + (wopts.bookType=="biff2"?"xls":wopts.bookType));
    }
    function s2ab(s) {
        if (typeof ArrayBuffer !== 'undefined') {
            var buf = new ArrayBuffer(s.length);
            var view = new Uint8Array(buf);
            for (var i = 0; i != s.length; ++i) view[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        } else {
            var buf = new Array(s.length);
            for (var i = 0; i != s.length; ++i) buf[i] = s.charCodeAt(i) & 0xFF;
            return buf;
        }
    }
</script>