http请求post,返回excel文件,并接收

1.post的方法里要加responseType: arraybuffer参数,不然下载的excel会乱码

2.使用{type: "application/vnd.ms-excel"}的写法,可以保存为xls格式的excel文件(兼容老版本)。而使用“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”则会保存为xlsx

3.返回结果为下载excel文档链接,使用window.open(result)即可

4.使用增加节点调用click方法,而不使用window.open(objectUrl)方法,是防止被浏览器当插件屏蔽弹出连接

5.给文件设定名字,直接在a标签的download属性中设置即可

$http.post({
     url:staffRoster/exportStaffrosterTemplate,
     data:sendData,
     responseType: arraybuffer
    }).success(function(res){
        var blob = new Blob([res], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"});
        var objectUrl = URL.createObjectURL(blob);
        var a = document.createElement("a");
        document.body.appendChild(a);
        a.style = "display: none";
        a.href = objectUrl;
        a.download = 员工信息表;
        a.click();
        document.body.removeChild(a);
    })
$http.post({ url:staffRoster/exportStaffrosterTemplate, data:sendData, responseType: arraybuffer }).success(function(res){ var blob = new Blob([res], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}); var objectUrl = URL.createObjectURL(blob); var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; a.href = objectUrl; a.download = 员工信息表; a.click(); document.body.removeChild(a); })
1.post的方法里要加responseType: arraybuffer参数,不然下载的excel会乱码 2.使用{type: "application/vnd.ms-excel"}的写法,可以保存为xls格式的excel文件(兼容老版本)。而使用“application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”则会保存为xlsx 3.返回结果为下载excel文档链接,使用window.open(result)即可 4.使用增加节点调用click方法,而不使用window.open(objectUrl)方法,是防止被浏览器当插件屏蔽弹出连接 5.给文件设定名字,直接在a标签的download属性中设置即可 $http.post({ url:staffRoster/exportStaffrosterTemplate, data:sendData, responseType: arraybuffer }).success(function(res){ var blob = new Blob([res], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"}); var objectUrl = URL.createObjectURL(blob); var a = document.createElement("a"); document.body.appendChild(a); a.style = "display: none"; a.href = objectUrl; a.download = 员工信息表; a.click(); document.body.removeChild(a); })
经验分享 程序员 微信小程序 职场和发展