文件导出是web应用里最常见的功能,特别是后台系统。
如下,对导出功能进行代码整理:
/**
*客户端js导出csv这种字符型文档
*调用方法 Z.export(tableId,fileName);
*table的ID,filename导出的文件名
*同时支持传参数给后台生成Excel
*
*author zhanggongzi
*web http://www.qingqingjianji.com/
*date 2018-8-22 17:25:10
*/
(function(){
var jsExport = {};
jsExport.VERSION = "1.0.0";
//导出csv文件,str = "列名1,列名2,列名3n值1,值2,值3";
jsExport.exportCsv = function(str,fileName){
var fileName = fileName || "export",
str = encodeURIComponent(str),
//ufeff因为csv文件开头不能留空
csv = "data:text/csv;charset=utf-8,ufeff";
var a = document.createElement("a");
a.href = csv+str;
a.download = fileName+".csv";
a.style.display = "none";
document.body.appendChild(a);
a.click();
setTimeout(function(){
document.body.removeChild(a);
},10);
}
//遍历表格内容返回数组
jsExport.getTableText = function(id){
var mytable = document.getElementById(id);
var data = [];
for(var i=0,rows=mytable.rows.length; i
for(var j=0,cells=mytable.rows[i].cells.length; j
if(!data[i]){
data[i] = new Array();
}
data[i][j] = mytable.rows[i].cells[j].innerHTML;
}
}
return data;
}
//把获取的表格数组转字符串
jsExport.dataToString = function(data){
var list = [];
if(Object.prototype.toString.apply(data) == "[object Array]"){
for(var i=0,j=data.length;i
list.push(data[i].join(","));
}
}
return list.join("n");
}
jsExport.export = function(tableId,fileName){
if(!tableId) return;
var tableData = this.getTableText(tableId);
var exportStr = this.dataToString(tableData);
var isIE = !!window.ActiveXObject || "ActiveXObject" in window;
if (isIE){
alert("IE浏览器不支持客户端导出,请使用谷歌浏览器!");
return false;
}else{
this.exportCsv(exportStr,fileName);
}
//IE不管是用ActiveXObject("Excel.Application")还是msSaveOrOpenBlob方法体验都极差
// if (isIE && window.navigator.msSaveOrOpenBlob){
// var blob = new Blob([decodeURI(encodeURI(exportStr))], {
// type: "text/csv;charset=utf-8;"
// });
// navigator.msSaveBlob(blob, fileName+'.csv');
// }else{
// this.exportCsv(exportStr,fileName);
// }
}
//通过链接url传参数给后台生成Excel文件
//url = http://www.xx.com/xx/xx?serviceId=xx&start_date=20180808&end_date=20181010";
jsExport.toAExport = function(url){
var a = document.createElement('a');
a.style.display = 'none';
a.href = url;
document.body.appendChild(a);
a.click();
setTimeout(function() {
document.body.removeChild(a);
}, 100);
}
//通过表单提交下载
//var params = {
// start_date:20180808,
// end_date:20181010,
// serviceId:'xx'
//};
//var actionUrl = "http://www.xx.com/xx/xx";
jsExport.toFormExport = function(actionUrl,parms,type){
var form = document.createElement("form");
form.style.display='none';
form.action = actionUrl;
form.method= type || "post";
document.body.appendChild(form);
for(var key in parms){
var input = document.createElement("input");
input.type = "hidden";
input.name = key;
input.value = parms[key];
form.appendChild(input);
}
form.submit();
setTimeout(function(){
document.body.removeChild(form);
},10);
}
window.Z = jsExport;
})();
网友评论