1. 程式人生 > >使用AngularJS匯出/下載excel檔案

使用AngularJS匯出/下載excel檔案

通常下載一個檔案用

window.location.href = "介面內容"

就能實現下載一個檔案的需求。

但是如果遇到一些特殊的需求,比如說需要在請求頭重加一些屬性和值,這樣window.location.href就不能滿足了。但是可以用angularJS自帶的$http來請求。

 $http({
                url: '你的介面內容',
                method: "GET",//介面方法
                params: {
                    //介面引數
                },
                headers: {
                    'Content-type': 'application/json'
                },
                responseType: 'arraybuffer'
            }).success(function (data, status, headers, config) {
                var blob = new Blob([data], {type: "application/vnd.ms-excel"});
                var objectUrl = URL.createObjectURL(blob);
                var a = document.createElement('a');
                document.body.appendChild(a);
                a.setAttribute('style', 'display:none');
                a.setAttribute('href', objectUrl);
                var filename="充值記錄.xls";
                a.setAttribute('download', filename);
                a.click();
                URL.revokeObjectURL(objectUrl);
            }).error(function (data, status, headers, config) {
            });

以上程式碼就可以下載excel.

接下來畫一下重點:

1.responseType: 'arraybuffer',這個屬性一定要新增上,不然返回資料型別會出錯。

2.var blob = new Blob([data], {type: "application/vnd.ms-excel"});

匯出檔案的格式是在這裡定義。

其實返回檔案的格式有很多種定義:

application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8
application/vnd.ms-excel

關鍵是要選擇哪一種是自己需要的

以上。

後續:

angularjs 1.6之後$http沒有success,error方法,所以你框架如果是1.6以上的話,按照以上寫會報如下錯:

 $http(...).success is not a function。。。。。

改成如下格式:

$http({
    url: '',
    method: 'get'
}).then(function (data){
    .....
})