利用xlsx前端导出excel表格

<script lang="javascript" src="dist/xlsx.full.min.js"></script>
复制代码

$ npm install xlsx
复制代码

$ bower install js-xlsx
复制代码


三种方式去引入xlsxjavascript


在项目里 咱们可能会根据一个table去导出数据,也有可能根据数组来导出数据java


  • aoa_to_sheet converts an array of arrays of JS data to a worksheet.
  • json_to_sheet converts an array of JS objects to a worksheet.
  • table_to_sheet converts a DOM TABLE element to a worksheet.
  • sheet_add_aoa adds an array of arrays of JS data to an existing worksheet.
  • sheet_add_json adds an array of JS objects to an existing worksheet.


这是官网上的 几种方式,  由于我在项目里使用了table导出和 数组,那么我运用的导出方式则是npm

  • aoa_to_sheet converts an array of arrays of JS data to a worksheet.
  • table_to_sheet converts a DOM TABLE element to a worksheet.


首先说一下 table表格如何去导出exceljson

function export2Excel(){
   function saveAs(obj, fileName) {//固然能够自定义简单的下载文件实现方式  var tmpa = document.createElement("a");
  tmpa.download = fileName || "下载";
  tmpa.href = URL.createObjectURL(obj); //绑定a标签
  tmpa.click(); //模拟点击实现下载
  setTimeout(function () { //延时释放
    URL.revokeObjectURL(obj); //用URL.revokeObjectURL()来释放这个object URL
  }, 100);
};
function s2ab(s){
  if(typeof ArrayBuffer !== "undefined"){
    var buf  =  new ArrayBuffer(s.length);
    var view  =  new Uint8Array(buf);
    for(var i=0;i!=s.length;++i){
      view[i] = s.charCodeAt(i) & 0xFF;
    };
    return buf;
  }else{
    var buf  =  new ArrayBuffer(s.length);
    for(var i=0;i!=s.length;++i){
      buf[i] = s.charCodeAt(i) & 0xFF;
    };
    return buf;
  }
};
var wb = xlsx.utils.table_to_book(document.getElementById(tableId));
var wbout = xlsx.write(wb,{bookType:'xlsx',type:'binary'});
saveAs(new Blob([s2ab(wbout)],{type:'application/octet-stream'}),你想要的名字+".xlsx");

}
复制代码

而后是数组数组

function export2Excel(){
function getColNumber (str) {
  var n = 0;
  var s = str.match(/./g);//求出字符数组
  var j = 0;
  for (var i = str.length - 1, j = 1; i >= 0; i--, j *= 26) {
    var c = s[i].toUpperCase();
    if (c < 'A' || c > 'Z') {
      return 0;
    }
    n += (c.charCodeAt(0) - 64) * j;
  }
  return n;
}
  function saveAs(obj, fileName) {//固然能够自定义简单的下载文件实现方式  var tmpa = document.createElement("a");
  tmpa.download = fileName || "下载";
  tmpa.href = URL.createObjectURL(obj); //绑定a标签
  tmpa.click(); //模拟点击实现下载
  setTimeout(function () { //延时释放
    URL.revokeObjectURL(obj); //用URL.revokeObjectURL()来释放这个object URL
  }, 100);
};
function s2ab(s){
  if(typeof ArrayBuffer !== "undefined"){
    var buf  =  new ArrayBuffer(s.length);
    var view  =  new Uint8Array(buf);
    for(var i=0;i!=s.length;++i){
      view[i] = s.charCodeAt(i) & 0xFF;
    };
    return buf;
  }else{
    var buf  =  new ArrayBuffer(s.length);
    for(var i=0;i!=s.length;++i){
      buf[i] = s.charCodeAt(i) & 0xFF;
    };
    return buf;
  }
};
var wb ={          //本身去定义  SheetNames里
  SheetNames:[],
  Sheets:{sheet1:''}
};

var ws = xlsx.utils.aoa_to_sheet(newOption.jsonData);
wb.SheetNames.push('Sheet1');
wb.Sheets['Sheet1'] = ws;
var widthArr =[];
 var   widthArrLength  = getColNumber(wb.Sheets.Sheet1['!ref'].split(":")[1].replace(/\d+/g,''));
 for( var j  = 0 ; j< widthArrLength;j++){
    widthArr.push({width:newOption.initCeilWidth})
  }
wb.Sheets.Sheet1['!cols']= newOption.cols.length > 0 ? newOption.cols :  widthArr;
var wbout = xlsx.write(wb,{bookType:'xlsx',type:'binary'});
saveAs(new Blob([s2ab(wbout)],{type:'application/octet-stream'}),你想要的名字+".xlsx");

}复制代码

固然咱们也简单的进行了融合 这个函数能够放到大家各位的公共方法里,bash

用法:app

若是是table,则传入tableId,若是是 json,则传入jsondata。cols是excel每列的宽度函数

格式为:cols=[{width:40},]ui

var option={
    tableId:'',
    jsonData:{},
    name:'导出',
    nameEng:'export',  //项目要求作过双语 因此按状况能够删除
    cols:[],
    initCeilWidth:20
  }复制代码


export2ExcelCommon(option){
  var module={
    tableId:'',
    jsonData:{},
    name:'导出',
    nameEng:'export',  //项目要求作过双语 因此按状况能够删除
    cols:[],
    initCeilWidth:20
  }
   var newOption =  Object.assign(module,option);
  function getColNumber (str) {
    var n = 0;
    var s = str.match(/./g);//求出字符数组
    var j = 0;
    for (var i = str.length - 1, j = 1; i >= 0; i--, j *= 26) {
      var c = s[i].toUpperCase();
      if (c < 'A' || c > 'Z') {
        return 0;
      }
      n += (c.charCodeAt(0) - 64) * j;
    }
    return n;
  }
  function saveAs(obj, fileName) {//固然能够自定义简单的下载文件实现方式
    var tmpa = document.createElement("a");
    tmpa.download = fileName || "下载";
    tmpa.href = URL.createObjectURL(obj); //绑定a标签
    tmpa.click(); //模拟点击实现下载
    setTimeout(function () { //延时释放
      URL.revokeObjectURL(obj); //用URL.revokeObjectURL()来释放这个object URL
    }, 100);
  };
  function s2ab(s){
    if(typeof ArrayBuffer !== "undefined"){
      var buf  =  new ArrayBuffer(s.length);
      var view  =  new Uint8Array(buf);
      for(var i=0;i!=s.length;++i){
        view[i] = s.charCodeAt(i) & 0xFF;
      };
      return buf;
    }else{
      var buf  =  new ArrayBuffer(s.length);
      for(var i=0;i!=s.length;++i){
        buf[i] = s.charCodeAt(i) & 0xFF;
      };
      return buf;
    }
  };

  if(newOption.tableId && JSON.stringify(newOption.jsonData) =='{}'){
    var wb = xlsx.utils.table_to_book(document.getElementById(newOption.tableId));
  }else if(!newOption.tableId && JSON.stringify(newOption.jsonData)!='{}'){

    var wb ={
      SheetNames:[],
      Sheets:{sheet1:''}
    };
    var ws = xlsx.utils.aoa_to_sheet(newOption.jsonData);
    wb.SheetNames.push('Sheet1');
    wb.Sheets['Sheet1'] = ws;
  };
  var widthArr =[];
   var   widthArrLength  = getColNumber(wb.Sheets.Sheet1['!ref'].split(":")[1].replace(/\d+/g,''));
   for( var j  = 0 ; j< widthArrLength;j++){
      widthArr.push({width:newOption.initCeilWidth})
    }
  wb.Sheets.Sheet1['!cols']= newOption.cols.length > 0 ? newOption.cols :  widthArr;
  var wbout = xlsx.write(wb,{bookType:'xlsx',type:'binary'});
    if(window.i18n.locale=='zh'){   
      saveAs(new Blob([s2ab(wbout)],{type:'application/octet-stream'}),newOption.name+".xlsx");
    }else{
      saveAs(new Blob([s2ab(wbout)],{type:'application/octet-stream'}),newOption.nameEng+".xlsx");
    }
};复制代码

最后但愿能帮助到各位!spa

相关文章
相关标签/搜索