[英]Export an HTML table to Excel
我已經創建了一個應用程序,該應用程序基於JSON數據集填充表,並且我想將過濾的數據存儲到Excel文件(甚至CSV)中。 我有兩個腳本文件,app.js和mainController.js(分開以獲得更清晰的代碼),一個視圖和索引文件(當然還有引導程序)。 這是app.js:
(function () {
"use strict";
var app = angular.module('customAudience', ['ngRoute']);
app.config(function ($routeProvider) {
$routeProvider
.when('/', {
controller: 'mainController',
templateUrl: 'views/mainPage.html'
})
.otherwise({
redirectTo: '/'
});
});
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"xmlns="http://www.w3.org/TR/REC-
html40"><head><!--[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;
}
};
});
}());
這是我的mainController.js:
(function () {
var mainController = function ($scope, $http, Excel, $timeout) {
$scope.sortType = 'PhoneNumber'; //set the default sort type
$scope.sortReverse = false; //set the default sort order
$scope.searchElement = ''; //set the default search/filter term
$scope.items = [];
$http.get('data/data.json').then(function (response) {
$scope.items = response.data;
});
$scope.exportToExcel = function (tableId) { // ex: '#my-table'
$scope.exportHref = Excel.tableToExcel(tableId, 'sheet name');
$timeout(function () {
location.href = $scope.fileData.exportHref;
}, 100); // trigger download
};
};
angular.module('customAudience').controller('mainController',
['$scope', '$http', 'Excel', '$timeout', mainController]);
}());
我的桌子上有一個ID,上面寫着“ mytable”,並將其傳遞給函數。
我得到的錯誤是:
TypeError:無法讀取e。(angular.js:5507)在angular.js:5784處angular.js:17855在mainController.js:19處未定義的屬性'exportHref'*
我已經使用https://gist.github.com/umidjons/352da2a4209691d425d4作為指南,但這是行不通的。
你們中有沒有人在AngularJS中將HTML表導出到Excel?
我想念什么嗎?
請注意,我使用的是Mac,這有什么區別嗎?
是否有另一種更干凈的導出數據的方法-像CSV文件一樣?
嘗試通過$ scope.exportHref在$ scope.exportToExcel方法中更改location.href值; 沒有fileData。
$timeout(function () { location.href = $scope.exportHref; }, 100); // trigger download
這對我行得通。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.