r/GoogleAppsScript • u/kevingjonathan • Nov 18 '19
Using Google Script to Input Google Drive Files' URLs into Google Sheets
Sorry in advance, but I think I should start by saying I'm not a dev nor do I have any dev knowledge. And I'm really hoping you could help me with this.
Scenario:
I have a folder in My Drive with several PDFs
I have a Google sheet with 2 columns, first column is "Name" and second column is "Document". The first column is filled with several names and the second column is entirely empty
What i want to do:
Import the URLs/links of the PDFs into the "Document" columns corresponding to the names. So John's PDF document should be in the same row with John's name
Someone from StackOverflow helped me come up with this script but it doesn't work:
function main () {
files = DriveApp.getFilesByType("application/pdf");
var names = [];
var links = [];
while (files.hasNext()) {
var file = files.next();
names.push(file.getName());
links.push(file.getUrl());
}
var newSpreadsheet = SpreadsheetApp.create("My favourite pdf");
Logger.log(newSpreadsheet.getUrl());
var newSheet = newSpreadsheet.getSheets()[0];
var a = newSheet.getRange("A1:A"+names.length );
var b = newSheet.getRange("B1:B"+names.length );
a.setValues([names]);
b.setValues([links]);
}1
u/harpsichord_cadenza Nov 18 '19 edited Nov 18 '19
Something like this might work. I used google docs for testing, but I think it will work for any file type. It's not very optimized either.
function myFunction() {
var spreadsheet = SpreadsheetApp.getActive();
var nameSheet = spreadsheet.getSheetByName([Enter the sheet name here]);
var nameSheetDataRange = nameSheet.getDataRange();
var nameSheetData = nameSheetDataRange.getValues();
var pdfFolder = DriveApp.getFolderById([Enter the folder ID here]);
var folderIndex = pdfFolder.getFiles();
while ( folderIndex.hasNext() )
{
var file = folderIndex.next();
var url = file.getUrl();
var name = file.getName();
for ( var index = 0; index < nameSheetData.length; ++ index )
{
if ( nameSheetData[index][0] == name )
nameSheetData[index][1] = url;
}
}
nameSheetDataRange.setValues(indexData);
}I'm not sure how your file names are set up and it might take a bit of work, but hope it will give you a start. It worked for me using google Docs with file names that match cell names in column A of a spreadsheet. It posted a URL link in column B.
1
u/harpsichord_cadenza Nov 18 '19
The last line should actually read:
nameSheetDataRange.setValues(nameSheetData)
1
u/kevingjonathan Nov 19 '19
A friend help me figure it out: