我正在使用AngularJs和C#开发应用程序,此应用程序具有导出和下载文件.xls的功能,但是当我单击下载文件的按钮时,响应为“ about:blank#blocked”浏览器的新标签。
HTML代码:
<button class="btn btn-success" ng-click="exportInfo()">
<i class="fa fa-file-excel-o"></i>Export
</button>
JavaScript代码:
$scope.exportInfo = function () {
if ($route.current.loadedTemplateUrl.indexOf('Index.html') > 0) {
InfoService.getInfo().then(function (e) {
$scope.info = angular.fromJson(e.data);
});
}
};
$scope.$watch('info', function (newValue, oldValue) {
if (newValue != undefined && newValue.length > 0) {
$scope.sleep = function (time) {
return new Promise(function (resolve) { setTimeout(resolve, time); });
};
angular.element("#infoTable").ready(function () {
$scope.sleep(500).then(function () {
//code to run here after the delay
var exportHref = Excel.tableToExcel('#infoTable', 'info');
window.open(exportHref);
});
});
}
});
app.factory('Excel', function ($window) {
var uri = 'data:application/vnd.ms-excel;base64,',
template = '<html xmlns:o="urn:schemas-microsoft-com:office:office" xmlns:x="urn:schemas-microsoft-com:office:excel"><head <meta http-equiv="Content-Type" content="text/html; charset=UTF-8"><!--[if gte mso 9]><xml><x:ExcelWorkbook><x:ExcelWorksheets><x:ExcelWorksheet><x:Name>{worksheet}</x:Name><x:WorksheetOptions><x:DisplayGridlines/></x:WorksheetOptions></x:ExcelWorksheet></x:ExcelWorksheets></x:ExcelWorkbook></xml><![endif]--></head><body><table>{table}</table></body></html>',
base64 = function (s) { return $window.btoa(unescape(encodeURIComponent(s))); },
format = function (s, c) { return s.replace(/{(\w+)}/g, function (m, p) { return c[p]; }) };
return {
tableToExcel: function (tableId, worksheetName) {
var table = $(tableId),
ctx = { worksheet: worksheetName, table: table.html() },
href = uri + base64(format(template, ctx));
return href;
}
};
});
注意:这在Mozilla Firefox浏览器中正常运行,但在其他浏览器中则无效。