1

I have a CSV file uploaded to a Google Drive folder. Its column A has different names of people. Each name has its own google sheet. I need each name(their data) to be imported to their corresponding google sheet.

If the source data is a google sheet, I can do it like this(see below). But, I have zero idea how to do it if my source data is a csv file:

function myFunction() {
  var ss = SpreadsheetApp.getActiveSpreadsheet().getSheetByName("Testname");
  var lr = ss.getLastRow();
  
  for (i=2; i<=lr; i++) {
    var conditionRange = ss.getRange(i,1).getValue();
      if (conditionRange == "John") {
        // All rows with John name will be imported to John's googlesheet

CSV File

1 Answer 1

1

Solution:

Use Utilities.parseCsv to retrieve the row data from your csv. With this, you can retrieve a 2D array with the csv data, which you can then loop through.

Code snippet:

function myFunction() {
  const csvFileId = "YOUR_CSV_FILE_ID";
  const csv = DriveApp.getFileById(csvFileId);
  const csvBlob = csv.getBlob();
  const csvData = Utilities.parseCsv(csvBlob.getDataAsString());
  csvData.shift(); // Remove headers
  for (let i = 0; i < csvData.length; i++) {
    if (csvData[i][0] == "John") {
      // All rows with John name will be imported to John's googlesheet
    }
  }
}

Note:

  • The loop process could probably be made more efficient, but without knowing what exactly you are doing in each iteration, I prefer leaving it as it is.
  • I assumed that you know the CSV file id, so it can be retrieved via DriveApp.getFileById. If that's not the case, please clarify what you do know about this file (name, parents, etc.) and I will modify the snippet accordingly.
Sign up to request clarification or add additional context in comments.

4 Comments

Thanks for the info. Yes, I know the ID of the CSV file and Folder ID. But, now I'm getting this error(Exception: Could not parse text) on line 13. The script below is the line 13th: var csvData = Utilities.parseCsv(fileBlob.getDataAsString());
@cgstats I cannot reproduce this. This is most likely related to the specific data in your csv. Therefore, in order to debug this, can you provide an example csv which can be used to reproduce this? (could be related to this, for example).
@cgstats Hi, was your issue solved?
Thanks for checking in. I haven't tried fixing it again caused by pile of work. I will update here. Sorry.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.