AngularJS $http-post - 将二进制文件转换为 excel 文件并下载

问题描述

只是注意到由于 IE8/9 而无法使用它,但我还是会推送提交……也许有人觉得它有用

这实际上可以通过浏览器完成,使用blob. 注意 Promise 中的responseType和 代码success

$http({
    url: 'your/webservice',
    method: "POST",
    data: json, //this is your json data string
    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"});
    var objectUrl = URL.createObjectURL(blob);
    window.open(objectUrl);
}).error(function (data, status, headers, config) {
    //upload failed
});

虽然它存在一些问题,例如:

  1. 它不支持IE 8 和 9
  2. 它会打开一个弹出窗口以打开objectUrl可能被阻止的人
  3. 生成奇怪的文件名

它确实奏效了!

斑点 我测试过的 PHP 中的服务器端代码如下所示。我确定您可以在 Java 中设置类似的标头:

$file = "file.xlsx";
header('Content-disposition: attachment; filename='.$file);
header('Content-Length: ' . filesize($file));
header('Content-Transfer-Encoding: binary');
header('Cache-Control: must-revalidate');
header('Pragma: public');
echo json_encode(readfile($file));

编辑 20.04.2016

浏览器使以这种方式保存数据变得更加困难。一个不错的选择是使用filesaver.js。它为 提供了一个跨浏览器的实现saveAs,它应该替换success上面 Promise 中的一些代码。

解决方法

我在 Angular JS 中创建了一个应用程序,用于通过 $http post 下载 Excel 工作簿。

在下面的代码中,我以 JSON 的形式传递信息,并通过有角度的 $http 帖子将其发送到服务器 REST Web 服务 (java)。Web 服务使用来自 JSON 的信息并生成 Excel 工作簿。在 $http post 的成功正文中的响应中,我在该数据变量中获取二进制数据,但不知道如何将其转换并下载为 Excel 文件。

谁能告诉我一些将二进制文件转换为 Excel 文件并下载的解决方案?

我的代码如下所示:

$http({
        url: 'myweb.com/myrestService',method: "POST",data: json,//this is your json data string
        headers: {
           'Content-type': 'application/json'
        }
    }).success(function (data,status,headers,config) {

        // Here i'm getting excel sheet binary datas in 'data' 

    }).error(function (data,config) {

    });

相关问答

依赖报错 idea导入项目后依赖报错,解决方案:https://blog....
错误1:代码生成器依赖和mybatis依赖冲突 启动项目时报错如下...
错误1:gradle项目控制台输出为乱码 # 解决方案:https://bl...
错误还原:在查询的过程中,传入的workType为0时,该条件不起...
报错如下,gcc版本太低 ^ server.c:5346:31: 错误:‘struct...