简体   繁体   中英

Using Google Apps Script to copy .CSV file data to Google Sheets

I am needing to loop through each .CSV file in a source folder and copy the data from each file into a new sheet/tab in one Google Sheets file. I've found a couple of answers related to this topic but I'm getting errors with both code sets. Here's the code I'm attempting to build a solution from:

function appendCSV() {  
    var file = DriveApp.getFilesByName("myCSVFile.csv").next(); 
    var csvData = Utilities.parseCsv(file.getBlob().getDataAsString()); 
    var sheet = SpreadsheetApp.getActiveSheet(); 
    var lastRow=sheet.getLastRow(); 
    sheet.getRange(lastRow, 1, csvData.length, csvData[0].length).setValues(csvData);
}

Here's the first error I'm getting:

Cannot retrieve the next object: iterator has reached the end. (line 2, file "Code")

I can delete the .next() method from line 2 and then I get another error:

TypeError: Cannot find function getBlob in object FileIterator. (line 3, file "Code")

Can anyone identify what might be going wrong here?

You need to provide Spreadsheet Id and folder id. Also you may wish to change the sheet names of the created sheets/tabs.

function loadCSVFilesIntoSheets() { 
  var ss=SpreadsheetApp.openById('SpreadsheetId')
  var folder=DriveApp.getFolderById('folderId');
  var files=folder.getFilesByType(MimeType.CSV);
  while(files.hasNext()) {
    var file=files.next();
    var vA=Utilities.parseCsv(file.getBlob().getDataAsString());
    var ts=Utilities.formatDate(new Date(),Session.getScriptTimeZone(),"MM/dd/yy HH:mm:ss")
    var sh=ss.insertSheet(file.getName()+'-'+ts);
    sh.getRange(1,1,vA.length,vA[0].length).setValues(vA);
  }
}

Getting Spreadsheet Id: https://docs.google.com/spreadsheets/d/SpreadsheetIdHere/edit#gid=1655026329

Folder Id: https://drive.google.com/drive/folders/folder id here

DriveApp

Utilities.parseCsv()

Utilities.formatDate()

The first error that you are getting

Cannot retrieve the next object: iterator has reached the end. (line 2, file "Code")

occurs because apparently there isn't any file named myCSVFile.csv

var file = DriveApp.getFilesByName("myCSVFile.csv").next();

The second error occurs for the same reason.

First, you should double check that the filename is correct and that this file is owned or shared with the same account used to run the script.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2025 STACKOOM.COM