1. 程式人生 > >淺析CSV----內有程式碼,,去掉定製化的內容,可直接使用

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

首先認識一下CSV

   csv---泛指具有以下特徵的任何檔案

             純文字,使用某個字符集,比如ASCII,Unicode,EBCDIC或GB2312

             有不同行的記錄組成,

             每條記錄被分隔符分隔成欄位(典型分隔符有逗號,分號或製表符)

        每條記錄都有同樣的欄位序列

    一句話總結:CSV只是資料用逗號分隔而已的普通TXT檔案,實際你用記事本開啟,也就是一串逗號分隔的字元

上程式碼解析

用excel開啟的話,處理列名

用excel展示,將資料依次放入對應的列下

 

以本地方式儲存檔案

 最後,上程式碼

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(); }