在AngularJS中不更新頁面實現下載Excel功能

程式碼:

$http({url: "exportxlsx.php", method: "POST", data:form, headers:{ 'Content-Type': undefined} })
      .then(function successCallback(res) {
         if(res.data.errMsg) { alert("Data Error: " + res.data.errMsg); return false; }
         var blob = new Blob(["\ufeff", res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"});
         // var blob = new Blob(["\ufeff", res.data], {type:"application/vnd.ms-excel;charset=utf-8"});
         var objectUrl = URL.createObjectURL(blob);
         var anchor = angular.element('<a/>');
         anchor.attr({
            href: objectUrl,  //'data:attachment/csv;charset=utf-8,' + encodeURI(res.data),
            target: '_blank',
            download: 'filename.csv'
        })[0].click();
        form = null;
      }, function errorCallback(data) { console.log(data); });

其中

var blob = new Blob(["\ufeff", res.data], {type: "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=utf-8"});
 
var blob = new Blob(["\ufeff", res.data], {type:"application/vnd.ms-excel;charset=utf-8"});

兩種方式都可以使用,要注意的是資料最前端要加上:”\ufeff” 這樣產生的資料才不會變亂碼。