angular怎么通过$http服务实现excel导出

前后端分离,前端通过ng的$http传post到后端,后端返回responsetype为application/vns.ms-excel的数据,请问有什么方式才能让浏览器下载excel文件呢?

阅读 8.3k
2 个回答
// 创建a标签模拟下载
function exportExcel(params, filename) {
    return $http({
        url: '/api/exportExcel',
        method: "POST",
        headers: {
            'Content-type': 'application/json'
        },
        params: params,
        responseType: 'arraybuffer'
    }).success(function (data) {
        var blob = new Blob([data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        var objectUrl = URL.createObjectURL(blob);
        var a = document.createElement('a');
        document.body.appendChild(a);
        a.setAttribute('style', 'display:none');
        a.setAttribute('href', objectUrl);
        a.setAttribute('download', filename);
        a.click();
        URL.revokeObjectURL(objectUrl);
    });
}
$http({
        url: 'http://localhost:8083/console/devices/poi',
        method: "POST",
        data: {
            "email": "官方邮箱"
        },
        headers: {
            'Content-type': 'application/json'
        },
        responseType: 'arraybuffer'
    }).then(function(data, status, headers, config) {
        var blob = new Blob([data], { type: "application/vnd.ms-excel" });
        var objectUrl = URL.createObjectURL(blob);
        var aForExcel = $("<a><span class='forExcel'>下载excel</span></a>").attr("href", objectUrl);
        $("body").append(aForExcel);
        $(".forExcel").click();
        aForExcel.remove();
    })
撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进