其他分享
首页 > 其他分享> > 记-纯前端excle下载

记-纯前端excle下载

作者:互联网

var fileName = '下载的文件名';
var label = [{'labelName1':'excle头1'},{'labelName2':'excle头2'},{'labelName3':'excle头3'},{'labelName4':'excle头4'}];
var data = [{'labelName1':'excle内容1'},{'labelName2':'excle内容2'},{'labelName3':'excle内容3'},{'labelName4':'excle内容4'}]

data = typeof data !== 'boject' ? JOSN.parse(data) : data;
var excle = '<table>';
#设置表头
var row = '<tr align="left">';//设置表格中的样式左居中
for(var i = 0; i < label.length; i++){
 for(var key in label[i]){
  row += '<td>'+label[i][key]+'</td>';
 }
}

excle = row + '</tr>';

//设置数据
for(var i = 0; i < data.length; i++){
  var rowData = '<tr align="left">';
  for(var y =0; y < label.length; y++){
    for(var k in label[y]){
      if(label[y].hasOwnProperty(k)){
        rowData += '<td style="vnd.ms-excel.numberformat:@">'+(data[i][k] === null ? "" : data[i][k]) + '</td>';//vnd.ms-excel.numberformat:@ 输出为文本
      }
    }
  }
  excle += rowData + '</tr>';
}
excle += '</table>';

#excel文件的内容
var excelFile = "<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'>";
excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel; charset=UTF-8">';
excelFile += '<meta http-equiv="content-type" content="application/vnd.ms-excel';
excelFile += '; charset=UTF-8">';
excelFile += "<head>";
excelFile += "<!--[if gte mso 9]>";
excelFile += "<xml>";
excelFile += "<x:ExcelWorkbook>";
excelFile += "<x:ExcelWorksheets>";
excelFile += "<x:ExcelWorksheet>";
excelFile += "<x:Name>";
excelFile += "{worksheet}";
excelFile += "</x:Name>";
excelFile += "<x:WorksheetOptions>";
excelFile += "<x:DisplayGridlines/>";
excelFile += "</x:WorksheetOptions>";
excelFile += "</x:ExcelWorksheet>";
excelFile += "</x:ExcelWorksheets>";
excelFile += "</x:ExcelWorkbook>";
excelFile += "</xml>";
excelFile += "<![endif]-->";
excelFile += "</head>";
excelFile += "<body>";
excelFile += excel;
excelFile += "</body>";
excelFile += "</html>";
//以excle格式文件下载到本地
var uri = 'data:application/vnd.ms-excel;charset=utf-8,' + encodeURIComponent(excelFile);
var link = document.createElement("a");
link.href = uri;
link.style = "visibility:hidden";
link.download =fileName + ".xls";
document.body.appendChild(link);
link.click();
document.body.removeChild(link);

标签:前端,excelFile,label,link,var,excle,data,下载
来源: https://www.cnblogs.com/leonchan/p/11496099.html