最近做项目,就碰到一个导出excel表格的功能。原本是想利用web前台导出excel的,但是最后因为两点放弃了,第一点,因为中文乱码,第二点,有分页(在前台导出excel的话,只能导出表格当页的数据,不能导出全部的,所以这是有缺陷的。当然不是做不到,只是需要不断追加数据,这个就怪了),所以最后的方案就是由后台的小伙伴导出excel的文件流,然后我去请求他们的接口取。()
一、get请求
当然使用get请求时,没有半点毛病,可以把代码提出来看看。
window.open("/api/sims/exportDetail?msisdn="+handle($scope.searchMsisdn)+"&simState="
+ handle($scope.searchSimstate) +"&dateAdded="+ changeDate($scope.searchDateAdded,false)+
"&imei="+handle($scope.searchImei)+"&ratePlan="+ handle($scope.searchRatePlan)+
"&onlineState="+handle($scope.searchOnlineState));
明眼人一看就知道,这是直接调链接的,然后url里面有参数,主要它excel导出文件流是正确的,那前台这块这么写,铁定没错。
$event.target.href = "/api/sims/exportDetail?msisdn="+handle($scope.searchMsisdn)+"&simState="
+handle($scope.searchSimstate)+"&dateAdded="+changeDate($scope.searchDateAdded,false)+
"&imei="+handle($scope.searchImei)+"&ratePlan="+handle($scope.searchRatePlan)+
"&onlineState="+handle($scope.searchOnlineState);
二、post请求
说到post请求还真是没做过,首先我在想如果是直接调用链接的话,那我就怎么把参数传给后台。然后就出现了我下面的代码
$http({
url: 'api/sims/expchsdetails',
method: "POST",
data: {"iccids":chkIccids}
}).success(function (data, status, headers, config) {
$event.target.href = "api/sims/expchsdetails";
}).error(function (data, status, headers, config) {
//upload failed
}
);
因为我想着,那我就就先请求,再访问链接,总应该对了吧。但心想还是有点怪怪的,因为这个链接一直是这个跟参数没毛线关系啊。要是请求之后能改变下url就好了。作为代码人士的港湾stackoverflow还是不错的,经过搜索”angularjs post excel“ http://stackoverflow.com/questions/22447952/angularjs-http-post-convert-binary-to-excel-file-and-download。
最后代码就如下了:
$http({
url: 'api/sims/expchsdetails',
method: "POST",
data: {"iccids":chkIccids},
responseType: 'arraybuffer'
}).success(function (data, status, headers, config) {
//var filename = config.headers('Content-Disposition').split(';')[1].trim().substr('filename='.length);
var filename = "simDetail.xls";
var blob = new Blob([data], {type: "application/vnd.ms-excel"});
var objectUrl = URL.createObjectURL(blob);
//window.open(objectUrl);
$event.target.download = filename;
$event.target.href = objectUrl;
$event.target.click();
}).error(function (data, status, headers, config) {
//upload failed
}
);