angularjs 服务端下载execl

html

<button class="btn btn-sm btn-primary pull-right" ng-click="exportData($event)"><i class="fa fa-spinner fa-pulse hidden"></i>导出表格</button>

js

//导出数据
        $scope.exportData = function(e) {
            var arr = e.target.children[0].className.split(' ');
            var index = arr.indexOf('hidden');
            arr.splice(index, 1);
            e.target.children[0].className = arr.join(' ');
            e.target.disabled = true;

            function resetBtn(e) {
                e.target.children[0].className = e.target.children[0].className + ' hidden';
                e.target.disabled = false;
            }

            $http({
                method: 'get',
                url: $scope.baseUrl + 'sampleCenter/reception?part=seek&action=exportExcel',
                responseType: 'arraybuffer'
            }).then(function(response) {
                if (response.headers()['content-type'] == 'text/html; charset=utf-8') {
                    var encode = new TextDecoder('utf-8');
                    var data = JSON.parse(encode.decode(new Uint8Array(response.data)));
                    if (data.error) {
                        toaster.pop({
                            type: 'error',
                            body: data.error,
                            timeout: 0
                        });
                        resetBtn(e);
                    }
                } else {
                    var blob = new Blob([response.data], { type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" });
                    var objectUrl = URL.createObjectURL(blob);
                    var a = document.createElement('a');
                    a.href = objectUrl;
                    a.target = '_blank';
                    a.download = '表格';
                    document.body.append(a);
                    a.click();
                    a.remove();
                    resetBtn(e);
                }
            }, function() {
                toaster.pop({
                    type: 'error',
                    body: '下载失败请与管理员联系!',
                    timeout: 0
                });
                resetBtn(e);
            })
        }

 

posted @ 2020-07-30 20:32  小猪章鱼  阅读(138)  评论(0编辑  收藏  举报