angularjs 1.x导出Excel方法,常用的有2种
1. 直接导出table为xls
service中加入
homeServiceMoudule.factory('Excel',['$window', '$sce','ConfigService', '$localStorage',function($window, $sce, ConfigService,$localStorage){
var uri='data:application/vnd.ms-excel;base64,';
var 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>';
var base64=function(s){return window.btoa(window.unescape(encodeURIComponent(s)));};
var format=function(s,c){return s.replace(/{(\w+)}/g,function(m,p){return c[p];});};
return {
tableToExcel:function(tableId,worksheetName){
var table=window.$(tableId),
ctx={worksheet:worksheetName,table:table.html()},
href=uri+base64(format(template,ctx));
return href;
}
};
}]);
data:application/vnd.ms-excel
兼容旧版,导出的为2003的xls。
如果改成:
data:application/vnd.openxmlformats-officedocument.spreadsheetml.sheet
导出为2007的xlsx.在controller中引入'Excel'
然后编写调用
$scope.exportToExcel=function(tableId){
var exportHref=Excel.tableToExcel(tableId, 'worksheetName');
$timeout(function(){location.href=exportHref;},500);
};
html加入导出按钮
<button class="btn btn-link" style="float:right" ng-click="exportToExcel('#tableExcel')">
<span class="glyphicon glyphicon-share">导出Excel</span>
</button>
记得把要导出的table标签加上 id="tableExcel"
注意:
1.导出文件名随机,导出数字格式需要注意,可能被excel日期化,
2.在chrome浏览器中,我遇到了数据行数的bug,1600行没问题,多了就导出出错,页面会跳转到空白页,在Firefox正常。
2. 直接导出数据
需要引入2个工具:
在页面中引入xlsx.core.min.js 和alasql.js
用例:直接把数据导出的2007的xslx
controller中编写逻辑调用
//导出为excel
$scope.exportToExcel=function( ){ // ex: '#my-table'
var excelArrs = getExcelData();
alasql.promise('SELECT * INTO XLSX("fileName' + '.xlsx",{headers:true}) FROM ?',[excelArrs])
.then(function (data) {
if(data == 1){
$timeout(function(){
console.log('数据导出成功!');
})
}
});
};
//组装ecxel数据
function getExcelData() {
var var arr =[];
var columns = 30;
angular.forEach(dateList, function(data, index, datas) {
var newObj = {
column1:data.column1,
column2:data.column2
};
var column = 0;
if(data.hasOwnProperty('minList')) {
var minList = data.minList;
if(minList != null && minList.length > 0){
angular.forEach(minList, function(dataM, indexM, datasM) {
if(dataM){
if(dataM.value){
column++;
newObj["value"+indexM] = dataM.value;
if(dataM.predict)
newObj["date"+indexM] = dataM.date;
}
}
});
}
}
for(;column < columns ; column++){
newObj["value"+column] = "";
newObj["date"+column] = "";
}
arr.push(newObj);
});
return arr;
}
html中添加调用按钮
<button class="btn btn-link" ng-click="exportToExcel()">
<span class="glyphicon glyphicon-share">导出Excel</span>
</button>
注意
1. 导出数据数组的第一个元素的属性决定文件头,如果第一个只有2个属性,后面的数组元素就算有再多的属性值也不会被导出。所有需要把第一个元素写满属性。
2. 可命名导出文件名,但是不能命名表名