上传csv文件时删除空行

时间:2016-07-03 21:21:19

标签: javascript angularjs regex csv filereader

我有一个csv-reader指令,让我们的用户上传一个csv文件。我注意到,当我上传一个文字之间有空格的文件时,例如:
ABC
ABC
abc

abc

abc

这显示出来了。我想删除所有空行不知道该怎么做。 enter image description here

                var reader = new FileReader();
                reader.onload = function(e) {
                    var contents = e.target.result;
                    var rows = contents.split('\n');                

                    // Check if the last row is empty. This works
                    if(rows[rows.length-1] ===''){
                        rows.pop()
}
}


     // this doesn't work for some reason. It doesn't detect the '' in the middle of the arrays.

    for( var i=rows.length-1;i>0;i--){
      if(rows[i] === ''){
        rows.splice(i,1)
      }
    }

3 个答案:

答案 0 :(得分:1)

尝试使用Array.prototype.filter()

var rows = contents.split('\n').filter(function(str){
    return str;
}); 

答案 1 :(得分:0)

根据您显示的内容,您似乎想要检查csvModel中的每个项目是否为空字符串,而不是newValue

类似的东西:

for( var i=0 ;i< $scope.csvModel.length; i++){    
    if (csvModel[i] == "") {
        $scope.csvModel.splice(i,1);
    }
}

答案 2 :(得分:0)

var text = [];
var target = $event.target || $event.srcElement;
var files = target.files;

if(Constants.validateHeaderAndRecordLengthFlag){
  if(!this._fileUtil.isCSVFile(files[0])){
    alert("Please import valid .csv file.");
    this.fileReset();
  }
}

var input = $event.target;
var reader = new FileReader();
reader.readAsText(input.files[0], 'UTF-8');

reader.onload = (data) => {
  let csvData = reader.result;
  let csvRecordsArray = csvData.split(/\r\n|\n/);
  if (csvRecordsArray[csvRecordsArray.length - 1] === '') {
    csvRecordsArray.pop();
  }
  var headerLength = -1;
  if(Constants.isHeaderPresentFlag){
    let headersRow = this._fileUtil.getHeaderArray(csvRecordsArray, Constants.tokenDelimeter);
    headerLength = headersRow.length;
  }

  this.csvRecords = this._fileUtil.getDataRecordsArrayFromCSVFile(csvRecordsArray,
    headerLength, Constants.validateHeaderAndRecordLengthFlag, Constants.tokenDelimeter);
  if(this.csvRecords===null){
    this.csvRecords=[];
  }
  else if(this.csvRecords!==null) {
    if ((JSON.stringify(this.csvRecords[0])) === (JSON.stringify(this.csvFormate))) {
      alert("format matches");
      this.displayCsvContent = true;
      for (let i = 0; i < this.csvRecords.length; i++) {
        if (i !== 0) {
          this.csvRecords[i].push(this.recordInsertedFlag);
        }
      }

    }
    else {
      alert("format not matches");

    }
  }

  if(this.csvRecords == null){
    this.displayCsvContent=false;
    //If control reached here it means csv file contains error, reset file.
    this.fileReset();
  }
};

reader.onerror = function () {
  alert('Unable to read ' + input.files[0]);

};