What is the alternative to getContentAsString() fr

2019-03-02 12:42发布

I have a script that will get the content from a .csv file in Google drive and pull it in to a Google Sheet. The script uses the DocsList service which is deprecated. The below works as required but I want to transition the DocsList components to DriveApp to ensure it works for the foreseeable future.

The main issue I see is that the getContentAsString() method does not appear to be available for DriveApp. Is there a direct alternative to getContentAsString() or a combination of other elements that can achieve the same outcome as the below script?

function importFromCSV() {
  var fileName = "0B2n-RwpLExXnaXRBWG1aT3NLbm8";
  var FileId = DriveApp.getFileById("0B2n-RwpLExXnaXRBWG1aT3NLbm8");
  var files = DocsList.getFiles();
  var csvFile = "";

  for (var i = 0; i < files.length; i++) {
    if (files[i].getId() == fileName) {
      csvFile = files[i].getContentAsString();
      Logger.log(files[i]);
      break;
    }
  }

  var csvData = CSVToArray(csvFile, ",");
  var ss = SpreadsheetApp.getActiveSpreadsheet();
  var sheet = ss.getActiveSheet();
  for (var i = 0; i < csvData.length; i++) {
    sheet.getRange(i+1, 1, 1, csvData[i].length).setValues(new Array(csvData[i]));
  }
}

1条回答
beautiful°
2楼-- · 2019-03-02 12:59

The DriveApp file object has a getBlob() method, the blob object has a getDataAsString() method... You can chain both methods to get a string content.

Below is the full code, simplified as it should (there were other inconsistencies in your initial code , as already mentioned in your former question).

   function importFromCSV() {
      var id = "0B2n-RwpLExXnaXRBWG1aT3NLbm8";
      var file = DriveApp.getFileById(id);// get the file object
      var csvFile = file.getBlob().getDataAsString();// get string content
      Logger.log(csvFile);// check in the logger
      var csvData = CSVToArray_(csvFile);// convert to 2D array
      var ss = SpreadsheetApp.getActiveSpreadsheet();
      var sheet = ss.getActiveSheet();
      sheet.getRange(1,1, csvData.length, csvData[0].length).setValues(csvData);// write to sheet in one single step
    }

    function CSVToArray_(strData){
     var rows = strData.split("\n");
     Logger.log(rows.length);
     var array = [];
      for(n=0;n<rows.length;++n){
       if(rows[n].split(',').length>1){ 
       array.push(rows[n].split(','));
       }
       }
    Logger.log(array);
    return array;
    }
查看更多
登录 后发表回答