Save spreadsheet in a Specific Folder of GDrive - google-ads-api

I need help with this Google AdWords script: https://developers.google.com/adwords/scripts/docs/solutions/keyword-performance.
Every time I run this script in Google AdWords account (for my PPC campaign), it creates report (spreadsheet) and save it on my google drive.
I would like to save spreadsheet file to specific subfolder on my google drive (for example Report/Campaign01). I found the article which describes how to save spreadsheet to specific folder. But I don't know how edit this script and use it. Article describing this function is here:
http://www.freeadwordsscripts.com/2014/07/save-file-or-spreadsheet-in-specific.html
Can you help me solve the problem?

Assuming your folder and file names are unique, use can save to a folder this way
function myFunction() {
var folderIterator = DriveApp.getFoldersByName("YOUR_FOLDER_NAME");
while ( folderIterator.hasNext() ) {
var folder = folderIterator.next();
folder_count++;
var spreadsheet = SpreadsheetApp.create("YOUR_SPREADSHEET_NAME");
// INSERT YOUR SPREADSHEET LOGIC HERE.
// YOU CAN CREATE YOUR SHEET HOWEVER YOU WANT,
// SO LONG AS YOU HAVE YOUR ACTIVE SPREADSHEET OBJECT.
// EITHER WAY, IT WILL SAVE TO YOUR ROOT DIRECTORY.
// THIS LOGIC MOVES YOUR FILE BY ID FROM ROOT TO YOUR SELECTED FOLDER.
var files = DriveApp.getRootFolder().getFilesByName("YOUR_SPREADSHEET_NAME");
while ( files.hasNext() ) {
var file = files.next();
if ( spreadsheet.getId() == file.getId() ) {
Logger.log("Found File! Moving...");
folder.addFile(file);
DriveApp.getRootFolder().removeFile(file);
} else {
Logger.log("Wrong File, id[%s]" , file.getId());
}
}
}
}

Related

I changed the ownership of one of my google drive folders, but it still consumes from my storage

My google drive storage is running out of space. So, in order to free some space, I created a new google account and transferred the ownership of one of the largest folders in my original drive (~7 GB) to the new account's drive.
The problem is, that after 3 days of waiting, the folder is still consuming the storage of the original account's drive. I made sure that the new account is the owner of the folder, but the problem is still there.
Any ideas?
The problem is that changing the ownership of folder inside google drive does not change it for the subfolders and files, you have to change them separately or write an app script to search for file and subfolders owned by you and change the ownership.
Run the script below as your account, if you are using Google Workspace and you are the admin and need to do it to other accounts, then you need to get a service account first and run the code below.
Note:
This way makes a lot of noise with notifications on both sides, the old owner and the new one.
function ChangeFileOwnership(folder){
// New owner
var new_owner = '<Add new owner email>';
if (folder == null) {
var folderObj = DriveApp.getFolderById('<ID of parent folder>');
return ChangeFileOwnership(folderObj);
}
var fileIt = folder.searchFiles('"me" in owners');
while (fileIt.hasNext()) {
var file = fileIt.next();
Logger.log("Changing ownership of " + file.getName() + " to " + new_owner);
// Set the owner to be the new owner
try {
file.addEditor(new_owner);
}
catch(err){
Logger.log(err.message);
}
try {
file.setOwner(new_owner);
}
catch(err){
Logger.log(err.message);
}
}
// Get all the sub-folders and iterate
var folderIt = folder.getFolders();
while (folderIt.hasNext()) {
fs = ChangeFileOwnership(folderIt.next());
}
}

Is it possible to insert an image into a Google Sheets spreadsheet using a formula and Drive file path?

Google Drive files are shared out via a unique (and random) URL when uploaded. Is there a way to upload an image via a Sheets formula that uses the file path of the image, NOT the sharing URL?
Instead of using: https://drive.google.com/file/(sharing link)
The formula would use something like: Drive/Test/img.png or Drive/Test/img.gif
I have noticed that within the help for the IMAGE function in Google Sheets it explicitly states that you cannot use images hosted at drive.google.com but I'd like to know if there's another way to accomplish this.
Unfortunately this isn’t possible. As Google Drive supports the existence of multiple files with the same name in the same folder, a file path isn’t enough to uniquely identify a file and so the file ID is required regardless of whether it’s ‘file path’ is unique or not.
If you want to get a specific image in a specific folder, you will have to explore your drive as multiple folders and multiple files can have the same name.
function listOfFilesOfFolder() {
var myFolder = 'yourFolder';
var sh = SpreadsheetApp.getActiveSpreadsheet().getSheetByName('yourSheet');
sh.clear();
sh.appendRow(["name", "date", "URL", "id", "type"]);
var folders = DriveApp.getFoldersByName(myFolder)
var foldersnext = folders.next();
var data = [];
var files = foldersnext.getFiles();
while (files.hasNext()) {
var file = files.next();
data = [
file.getName(),
file.getLastUpdated(),
file.getUrl(),
file.getId(),
file.getMimeType()
];
sh.appendRow(data);
}
sh.getRange('F1').setFormula(`={"image";arrayformula(if(D2:D="",,if(left(E2:E,5)="image",IMAGE("https://docs.google.com/uc?export=view&id="&D2:D),)))}`)
}

google sheet: make a local copy of image link from a shared sheets

my frient shared his google sheet to me and the table contains image which is a link (url). How can i make a copy of this sheet and make all the image link to be local, so i want the image is copying to my local google drive automatically (so the link won't be broken if he delete his images files in future). Right now, if i make a copy of this document, then it still link to original image source.
How is it possible ? of course i don't want to manually copy them one by one from the link. Is there any better and faster way ?
https://docs.google.com/spreadsheets/d/1TkXwAd8rKbjnGfYEJVaOYBJwCZ7G7YfuSvmcDE6g8No/edit?usp=sharing
The OP wants to extract the image URL from a hyperlink formula, and save a copy of the image to their own Google Drive account.
This answer combines several elements from precedents on StackOverflow.
Since the images metadata is in the formula, the code uses the getFormulas() method rather than the "conventional" getValues(). Cells with no formula are empty strings; hence the test if (formula.length !=0){.
Get the file name without extension: REGEX: Capture Filename from URL without file extension. Ironically, this precedent doesn't use regular expressions but finds the position of the last / and the last . using lastIndexOf and getting a substring between those points. Note this solution fails on filenames with multiple periods, though there is an alternative solution for this scenario.
Get the file name from the url: Getting a Google Spreadsheet Cell's Image URL which combines regex and Javascript match.
Save a file to Google Drive: Need sheets script to save img to drive which is a simple and elegant solution for saving files.
Saving the file to Google Drive: When copying files using Apps Script from one folder to another any “Apps Script” files being copied end up in MyDrive not the specified folder - why? explains why the API is required to write the files to My Drive.
Note: In order to use this script, enable Drive API v2 at Advanced Google Services
On script editor, Resources -> Advanced Google Services; Turn on Drive API v2
function so5811567402() {
var ss=SpreadsheetApp.getActiveSpreadsheet();
var sheetName = "Table";
var sh = ss.getSheetByName(sheetName);
var rg=sh.getDataRange();
var lastColumn = sh.getLastColumn();
var lastRow = sh.getLastRow();
var formulas = rg.getFormulas();
for (var i in formulas) {
for (var j in formulas[i]) {
var formula = formulas[i][j];
if (formula.length !=0){
var regex = /image\("(.*)"/i;
var matches = formula.match(regex);
var imgurl = matches[1];
var filename = imgurl.substring(imgurl.lastIndexOf("/") + 1, imgurl.lastIndexOf("."));
//Logger.log(filename);
var image = UrlFetchApp.fetch(imgurl).getBlob().getAs('image/jpeg').setName(filename);
var FolderId = "Folder ID goes here";
var folder = DriveApp.getFolderById(FolderId);
var file = DriveApp.createFile(image);
Drive.Files.update({"parents": [{"id": folder.getId()}]}, file.getId());
}
}
}
}

How to write a script for automatically uploading/inserting images which are saved in team drive?

I have to insert images to google drive spreadsheet on the daily basis. The image is saved in the specific folder of team drive. Want to write a script so that the images can be inserted automatically once I press the "Macro Button".
The name-formatting of images is random (but can be renamed like 20190122US,20190122ASIA, let us assume this). For example, they are saved under team drive path:team drive\Daily\Testing. The type of file is GIF image. I have tried the below code, but can only insert the picture from Internet with url. I think the images in the team drive has different url or even don't have public url. Some people talks of Google Drive REST API v3. but I couldn't find it.
function insertImageOnSpreadsheet() {
// URL of spreadsheet.
var SPREADSHEET_URL = '--';
// Name of the specific sheet in the spreadsheet.
var SHEET_NAME = 'Sheet 1';
var ss = SpreadsheetApp.openByUrl(SPREADSHEET_URL);
var sheet = ss.getSheetByName(SHEET_NAME);
var response = UrlFetchApp.fetch('--');
var binaryData = response.getContent();
// Insert the image in cell E6.
var blob = Utilities.newBlob(binaryData, 'image/png', 'MyImageName');
sheet.insertImage(blob, 5, 1);
}
I expect to insert the pictures in team drive. ideally, the pictures can be inserted and be moved into a achieved folder in the same saved path:team drive\Daily\Testing\achieved files.

Google Spreadsheets: referencing automatically cell data from a dynamic list of files

I have a a list of invoices created with Google Spreadsheet. Now I would like to retrieve the data inside of those invoices to create another spreadsheet called "All" that contains a row for each invoice.
Name Phone Street
John 677 Main
Mary 897 Niceday
Is there any way to do that automatically instead of referencing cells one by one?
One more: imagine, I add a new invoice file, I would like that after addding it, the Name, Phone and Street inside it, were added automatically to the "All" file. Is possible?
If all of the files are located inside a single drive folder, then you can retrieve all of the data from each spreadsheet file and add it to your main spreadsheet file using an onOpen function.
function onOpen(){
// This active sheet.
var mainSpreadsheet = SpreadsheetApp.getActiveSheet();
// To store all of the invoice data
var invoiceData = [];
// Get all files inside a drive folder
var files = DocsList.getFolderById("DRIVE FOLDER ID").getFiles();
// For each file in the folder
for (var i in files) {
// Open the current spreadsheet in the interation
var thisSpreadsheet = SpreadsheetApp.openById(files[i].getId());
// Get the contents as an array and add it to invoiceData
invoiceData.push(thisSpreadsheet.getDataRange().getValues());
}
// Clear all content in active sheet
mainSpreadsheet.getDataRange.clearContent();
// Get the write range from the number of values inside invoiceData
var writeRange = mainSpreadsheet.getRange(1,1,invoiceData.length, invoiceData[0].length)
// Add the data to the spreadsheet.
writeRange.setValues(invoiceData);
}
This is an example and untested. It will vary depending on headings in your file but it should dget you started.

Resources