淺析CSV----內有代碼,,去掉定製化的內容,可直接使用

首先認識一下CSV

   csv---泛指具備如下特徵的任何文件app

             純文本,使用某個字符集,好比ASCII,Unicode,EBCDIC或GB2312this

             有不一樣行的記錄組成,spa

             每條記錄被分隔符分隔成字段(典型分隔符有逗號,分號或製表符)3d

        每條記錄都有一樣的字段序列excel

    一句話總結:CSV只是數據用逗號分隔而已的普通TXT文件,實際你用記事本打開,也就是一串逗號分隔的字符code

上代碼解析

用excel打開的話,處理列名

用excel展現,將數據依次放入對應的列下

 

以本地方式保存文件

 最後,上代碼blog

columns=[];
  csvSeparator = ',';
  exportList(){
    let tmpArr =  this.exportData;
    let csv = '\ufeff';
    for(let i in this.customList){
      //不顯示操做列
      // if(this.customList[i].checked && this.customList[i].value != 'item'){
      if(this.customList[i].checked ){
        if(this.customList[i].value != 'item'){
          this.columns.push(this.customList[i].value);
          const column = this.customList[i].label
          csv += '"' + (column.header || column) + '"';
          csv += this.csvSeparator;
        }
      }
    }
    //body
    tmpArr.forEach((record) => {
      let tmp ;
      csv += '\n';
      let stateNm = this.checkState('',record.state)
      record['LoadBalancerClass'] = '公網' ;
      record['ChargeType'] = '按需付費' ;
      record['state'] = this.checkState('',record.state)
      record['ExpireTime'] = '--' ;
      if(!record['vpc_name']){
        record['vpc_name'] = '--';
      }
      for (let i_1 = 0; i_1 < this.columns.length; i_1++) {
         const column = this.columns[i_1];
         if(column == 'business_ip' && record.eip_id !=null){
           tmp = record.business_ip;
           record.business_ip =  record.business_ip+'(內)' +'\r\n'+ record.eip_address+'(外)'
         }else if(column == 'business_ip' && record.eip_id ==null){
           tmp = record.business_ip;
           record.business_ip =  record.business_ip+'(內)' +'\r\n'+ '--(外)'
         }
         csv += '"' + this.resolveFieldData(record, column) + '"';
        column == 'business_ip' ? record.business_ip =  tmp : record.business_ip;
         if (i_1 < (this.columns.length - 1)) {
          csv += this.csvSeparator;
         }
      }

    });
    const blob = new Blob([csv], {
      type: 'text/csv;charset=utf-8;'
    });
    let newDate = new Date();
    let month=newDate.getMonth()+1;
    let day=newDate.getDate();
    let yearMonth = newDate.getFullYear()+''+(month<10 ? "0"+month:month)+(day<10 ? "0"+day:day);
    console.log(yearMonth)
    if (window.navigator.msSaveOrOpenBlob) {
      navigator.msSaveOrOpenBlob(blob, "SLB_INFO_"+ yearMonth + '.csv');
    } else {
      const link = document.createElement('a');
      link.style.display = 'none';
      document.body.appendChild(link);
      if (link.download !== undefined) {
        link.setAttribute('href', URL.createObjectURL(blob));
        link.setAttribute('download', "SLB_INFO_"+ yearMonth +  '.csv');
        link.click();
      } else {
        csv = 'data:text/csv;charset=utf-8,' + csv;
        window.open(encodeURI(csv));
      }
      document.body.removeChild(link);
    }
    this.refresh();
  }
相關文章
相關標籤/搜索