0

我的 Java REST 服务(POST 调用)使用 hssfWorkbook 提供一个 excel 文件作为响应,并以 xls 格式返回 excel。

response.getOutputStream();
hssfWorkbook.write(out);

我已经尝试过 Filesaver,但它适用于 JSON 作为响应。我没有找到任何方法在 Angular JS 中实现 excel 文件下载。请提出任何使用 Angular JS 的方法。

4

2 回答 2

1

试试这个它会工作。

API

httpServletResponse.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
httpServletResponse.setHeader("Content-Disposition",
                        "attachment; filename=sample.xlsx");
workbook.write(httpServletResponse.getOutputStream());
workbook.close();
httpServletResponse.getOutputStream().close();

$http 调用

    $scope.download = function() {
           $http({
                url: '/download',
                method: "POST",
                data: $scope.pagination,
                headers: {
                    'Content-type': 'application/json'
                },
                responseType: 'arraybuffer'
            }).success(function(data, status, headers, config) {
                var blob = new Blob([data], {
                    type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
                });
                saveAs(blob, "Sales_Summary_Report.xls");
            }).error(function(data, status, headers, config) {

            });
    }

HTML

<button ng-click="download()"> Download Excel </button>
于 2016-10-28T11:38:57.140 回答
0

对于 IE,您可以尝试msSaveOrOpenBlob其他浏览器提示,使用不可见的锚链接应该可以解决它,这样的代码对我很有用:

$http( /*your request details */ ).
            success(function(data) {
                var blob = new Blob([data], { type: 'application/vnd.ms-excel' }),
                    fileName = 'Sales_Summary_Report.xls';
                if (window.navigator.msSaveOrOpenBlob) {
                    window.navigator.msSaveOrOpenBlob(blob, fileName);
                } else {
                    var anchor = angular.element('<a/>');
                    anchor.css({ display: 'none' });
                    angular.element(document.body).append(anchor);
                    anchor.attr({
                        href: (window.URL || window.webkitURL).createObjectURL(blob),
                        target: '_blank',
                        download: fileName
                    })[0].click();
                    anchor.remove();
                }
            })
于 2016-10-28T12:02:51.330 回答