Sub topic 11
Importing a CSV from Drive with Apps Script
This chapter shows how to import a CSV file stored in Google Drive using a short Apps Script function. It assumes you can use File > Import, you know what a CSV file is, and you have used basic formulas such as TRIM and TEXT. You don't need to know JavaScript well. Each line of the script is explained.
Why use a script
File > Import works well for a one-off file. A script is better in these cases:
- You import the same file every week and want one click instead of the dialog.
- The file is in Drive, but IMPORTDATA can't reach it. IMPORTDATA needs a public URL.
- You want control over the target sheet name, the delimiter and the cleanup that happens after the import.
- You want the import to run on a schedule, with no one present.
The trade-off is maintenance. A script is code you own. It needs a one-time authorization, and it breaks if the file ID or the file layout changes.
The three-step pattern
Every CSV import script does the same three things.
- Read the file from Drive as text.
- Parse the text into a two-dimensional array, where each inner array is one row.
- Write the array into a sheet with a single
setValuescall.
Open the script editor
- Open the spreadsheet that will receive the data.
- Choose Extensions > Apps Script.
- Delete the placeholder function in the editor.
- Paste the code from the next section.
A script created this way is bound to the spreadsheet. That means SpreadsheetApp.getActiveSpreadsheet() returns the spreadsheet you opened.
The basic script
function importCsvFromDrive() {
const fileId = 'YOUR_FILE_ID';
const csvText = DriveApp.getFileById(fileId).getBlob().getDataAsString('UTF-8');
const rows = Utilities.parseCsv(csvText);
const sheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet('Imported');
sheet.getRange(1, 1, rows.length, rows[0].length).setValues(rows);
}Find the file ID
Open the file's sharing link in Drive. The link looks like https://drive.google.com/file/d/1AbC...xyz/view. The long string between /d/ and /view is the file ID. Replace YOUR_FILE_ID with it, and keep the quotation marks.
What each line does
| Line | What it does |
|---|---|
| `DriveApp.getFileById(fileId)` | Finds the file in Drive. It fails if the ID is wrong or you lack access. |
| `.getBlob()` | Gets the file's raw content as a blob, which is a chunk of bytes. |
| `.getDataAsString('UTF-8')` | Decodes the bytes into text using the UTF-8 encoding. |
| `Utilities.parseCsv(csvText)` | Splits the text into rows and fields and returns an array of arrays of strings. |
| `insertSheet('Imported')` | Adds a new sheet named Imported. It throws an error if that name already exists. |
| `getRange(1, 1, rows.length, rows[0].length)` | Selects a block that starts at row 1, column 1 and matches the data's size. |
| `setValues(rows)` | Writes all values in one call. |
Run it for the first time
- Click Save, then choose
importCsvFromDrivein the function menu. - Click Run.
- Google asks for permission. Review the requested access, choose your account, and allow it. The script needs access to Drive files and to your spreadsheets.
- Return to the spreadsheet. A new sheet named Imported holds the data.
If you run it a second time, it fails because the sheet already exists. The next sections fix that.
Why one setValues call matters
You could write the data cell by cell with setValue inside a loop. That works, but each call is a separate round trip to the Sheets service. A file with 10,000 rows and 10 columns would need 100,000 calls, and the script could run for minutes or hit the execution time limit. One setValues call sends the whole block at once and finishes in a second or two.
The rule is to build the full array in memory, then write it once.
Type conversion: what the script does differently
Utilities.parseCsv returns every field as a string. When setValues writes those strings, Sheets interprets them as if you had typed them into the cell. This has these effects:
42becomes the number 42.2026-03-05becomes a date.007becomes the number 7, and the leading zeros are lost.- A field that starts with
=is entered as a formula.
This matches the "Convert text to numbers, dates, and formulas" option in the import dialog when it is turned on. The script doesn't give you a switch. You get the conversion unless you prepare the cells first.
Keep leading zeros with a text format
To keep codes such as ZIP codes as text, set the column's number format to plain text before you write the data. The format @ means plain text.
function importCsvKeepZipAsText() {
const fileId = 'YOUR_FILE_ID';
const csvText = DriveApp.getFileById(fileId).getBlob().getDataAsString('UTF-8');
const rows = Utilities.parseCsv(csvText);
const sheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet('ImportedText');
// Column 3 holds ZIP codes in this example.
sheet.getRange(1, 3, rows.length, 1).setNumberFormat('@');
sheet.getRange(1, 1, rows.length, rows[0].length).setValues(rows);
}Order matters. The format must be set before setValues. If you set it afterward, the value has already been converted to the number 7 and the zeros are gone.
If you can't change the script, the formula from the pitfalls chapter repairs the data afterward, as long as every code has the same length:
=TEXT(A2, "00000")Make the script safe to run again
A script that fails on the second run isn't useful for a weekly job. Reuse the sheet if it exists, and clear the old data first.
function importCsvFromDriveRepeatable() {
const fileId = 'YOUR_FILE_ID';
const sheetName = 'Imported';
const csvText = DriveApp.getFileById(fileId).getBlob().getDataAsString('UTF-8');
const rows = Utilities.parseCsv(csvText);
if (rows.length === 0) {
throw new Error('The CSV file is empty.');
}
const ss = SpreadsheetApp.getActiveSpreadsheet();
const sheet = ss.getSheetByName(sheetName) || ss.insertSheet(sheetName);
sheet.clearContents();
sheet.getRange(1, 1, rows.length, rows[0].length).setValues(rows);
}Here is what changed:
getSheetByName(sheetName) || insertSheet(sheetName)uses the existing sheet, and creates one only when none exists.clearContents()removes old values but keeps formatting and column widths. Useclear()if you want to remove formatting too.- The empty-file check prevents an error. With zero rows,
rows[0]is undefined androws[0].lengthfails with a confusing message.
This is the equivalent of the "Replace current sheet" option in the dialog. To append instead, write the new rows below the last used row:
function appendCsvFromDrive() {
const fileId = 'YOUR_FILE_ID';
const rows = Utilities.parseCsv(
DriveApp.getFileById(fileId).getBlob().getDataAsString('UTF-8')
);
rows.shift(); // drop the header row so it is not repeated
if (rows.length === 0) return;
const sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('Imported');
const startRow = sheet.getLastRow() + 1;
sheet.getRange(startRow, 1, rows.length, rows[0].length).setValues(rows);
}getLastRow() returns the last row that contains data, so the new block starts directly under it.
Delimiters, encoding and locale
Other delimiters
Utilities.parseCsv assumes commas. For a semicolon-separated file, pass the delimiter as the second argument:
const rows = Utilities.parseCsv(csvText, ';');For a tab-separated file, use '\t'. The delimiter must be a single character. The same idea applies to the second argument of IMPORTDATA, such as =IMPORTDATA("https://example.com/data.csv", ";").
Encoding
getDataAsString('UTF-8') assumes the file is UTF-8. If accented letters appear as strange symbols, the file probably uses another encoding. Excel on Windows often saves CSV files as Windows-1252. Pass the encoding name instead:
const csvText = DriveApp.getFileById(fileId).getBlob().getDataAsString('windows-1252');A UTF-8 file saved with a byte order mark can leave an invisible character at the start of the first header. If a header lookup fails even though the name looks right, remove the character:
const cleaned = csvText.replace(/^\uFEFF/, '');Locale
The script doesn't use the spreadsheet locale for parsing the CSV, but setValues does use it when it interprets strings. A value such as 3,5 becomes a number in a spreadsheet set to a German locale, and it stays text in a US locale. The date 03/04/2026 is March 4 in the US and April 3 in the UK. Check File > Settings > Locale before you trust date columns.
Clean up after the import
Imported text often has stray spaces that break lookups. You can run a cleanup in the script, so the sheet is ready on arrival. Trimming the strings before writing is cheaper than formulas afterward:
const trimmed = rows.map(row => row.map(cell => cell.trim()));Place this line after parseCsv and write trimmed instead of rows. The result matches what this formula does in the sheet:
=ARRAYFORMULA(TRIM(A2:A))Use the formula when you want to leave the raw import untouched and keep the cleaned copy in another column.
After any import, check three things:
- Compare the row count with the file.
=COUNTA(A:A)should equal the number of lines, including the header. - Look for left-aligned numbers or dates. Text is left-aligned by default, numbers and dates are right-aligned.
- Spot-check a few rows with leading zeros, long ID numbers and special characters.
Limits and failure modes
| Symptom | Likely cause | Fix |
|---|---|---|
| `Exception: No item with the given ID could be found` | Wrong file ID, or your account can't open the file | Recheck the ID and the sharing settings |
| `Exception: The sheet name already exists` | `insertSheet` called with a name already in use | Use `getSheetByName` first |
| `The number of columns in the range must be at least 1` | Empty file | Add the empty-file check |
| `The number of columns in the data does not match the number of columns in the range` | Rows have different lengths | Pad rows to the same length, shown below |
| Script stops after about six minutes | Execution time limit for a single run | Import fewer rows per run, or split the file |
| Accented letters look wrong | Wrong encoding | Use the file's real encoding |
| Sheet becomes slow or the write fails | A spreadsheet can hold at most 10 million cells | Remove unused sheets and columns, or split the data |
The column mismatch error is the one you will meet most often, because setValues needs a perfect rectangle. A CSV with a ragged last line triggers it. Pad every row to the widest row:
const width = Math.max(...rows.map(r => r.length));
const rectangular = rows.map(r => r.concat(Array(width - r.length).fill('')));Then size the range with width and write rectangular. The spread in Math.max(...) works for a normal file. For a file with several hundred thousand rows, use a loop to find the maximum, because spreading that many arguments can exceed the engine's limit.
Large files have a second limit. The whole file is read into memory as one string and then as one array. Very large files can run out of memory or time. Split them, or keep only the columns you need.
Run the import automatically
To run the import on a schedule, open the clock icon (Triggers) in the Apps Script sidebar, then choose Add Trigger. Select your function, choose Time-driven, and pick an interval such as every day. The trigger runs under your account, so keep the Drive file in a place you will keep access to.
Exercise
Your script imports a CSV with a column of five-digit ZIP codes, and the code 02134 shows up as 2134. Name two ways to fix it, and say what must be true for each to work.
Show answer
First, set the column's number format to plain text with setNumberFormat('@') before calling setValues. It must run before the write, because afterward the value is already the number 2134. Second, repair the cells after the import with =TEXT(A2, "00000"). This works only if every code should have exactly five digits, so it fails for data with codes of other lengths.
Exercise
The weekly script throws an error on its second run saying the sheet name already exists. Rewrite the sheet-creation line so the script reuses the sheet, and name the call that clears old data while keeping formatting.
Show answer
Use const sheet = ss.getSheetByName('Imported') || ss.insertSheet('Imported'); where ss is the active spreadsheet. Call sheet.clearContents() before setValues. clearContents removes values and keeps formatting, while clear() removes both.
Exercise
setValues fails with a message that the number of columns in the data does not match the range. The CSV looks fine in a text editor. What is the likely cause, and how do you fix it?
Show answer
At least one row has fewer fields than the first row, often a short last line or a row with a missing trailing delimiter. setValues needs every row to have the same length. Find the widest row, pad shorter rows with empty strings using concat and Array(...).fill(''), and size the range to that width.