I am trying to save a spreadsheet to a specific folder on Drive using google app script. However, I cannot see a method that allows me to do so.
using:
SpreadsheetApp.create(name)
saves it directly to Drive, is there a way to save it in a folder?
Any help much appreciated.
How about these solutions? You can choose one of them freely.
SpreadsheetApp.create() cannot directly create in a special folder. It is created to the root folder. When you want to create new spreadsheet in a special folder, you can achieve using DriveApp and Drive API. The sample scripts are as follows.
1. Use DriveApp
When you use this, you can use by only copy and paste this to your script editor.
var fileId = SpreadsheetApp.create(name).getId();
var file = DriveApp.getFileById(fileId);
DriveApp.getFolderById("### folder ID ###").addFile(file);
file.getParents().next().removeFile(file);
Flow :
Create new spreadsheet to root folder.
Add a special folder to the parents of created spreadsheet.
Remove the root folder from the parents of created spreadsheet.
2. Use Drive API
This can create directly new spreadsheet to the special folder. When you use this, you can use by copy and paste this to your script editor. And then, please enable Drive API at Advanced Google Services and API console.
Drive.Files.insert({
"mimeType": "application/vnd.google-apps.spreadsheet",
"parents": [{"id": "### folder ID ###"}],
"title": name
});
Enable Drive API at Advanced Google Services
On script editor
Resources -> Advanced Google Services
Turn on Drive API v2
Enable Drive API at API console
On script editor
Resources -> Cloud Platform project
View API console
At Getting started, click Enable APIs and get credentials like keys.
At left side, click Library.
At Search for APIs & services, input "Drive API". And click Google Drive API.
Click Enable button.
References :
getParents()
addFile()
removeFile()
Advanced Google Services : https://developers.google.com/apps-script/guides/services/advanced
Drive API v2: https://developers.google.com/drive/v2/reference/
If I misunderstand your question, I'm sorry.
Updated at August 28, 2020:
By updating at July 27, 2020, addFile(File), addFolder(Folder), removeFile(File) and removeFolder(Folder) have been deprecated. Ref From July 27, 2020, file.moveTo(destination) and folder.moveTo(destination) are used.
By this, above sample script can be changed as follows.
From:
var folderId = "###";
var fileId = SpreadsheetApp.create("sample name").getId();
var file = DriveApp.getFileById(fileId);
DriveApp.getFolderById(folderId).addFile(file);
file.getParents().next().removeFile(file);
To:
var folderId = "###";
var fileId = SpreadsheetApp.create("sample name").getId();
var file = DriveApp.getFileById(fileId);
var folder = DriveApp.getFolderById(folderId);
file.moveTo(folder);
References:
file.moveTo(destination)
folder.moveTo(destination)
Related
I have designed a feedback system via Google Sheets and Apps Script. It works all good on My Drive. When I moved it to a Shared Drive, the "DriveApp" didn't like the change.
Based on this very useful article that John from Google shard with me, I activated Advanced Drive Service and used the method Drive.Drives.insert allows you to specify the Drive Id.
How can I specify a folder in a shared drive with this method? Like the one we have with DriveApp (DriveApp.getFolderByID). How would you do that?
From How can I specify a folder in a shared drive with this method? Like the one we have with DriveApp (DriveApp.getFolderByID). How would you do that?, I guessed that you might want to retrieve the folder information. If my understanding is correct, how about the following sample script?
Sample script 1:
When you can know the folder ID of the folder in a shared Drive, you can use the following script. Before you use this, please enable Drive API at Advanced Google services.
const folderId = "###"; // Please set the folder ID in a shared Drive.
// This sample uses Drive service (DriveApp).
const folder = DriveApp.getFolderById(folderId);
const folderName1 = folder.getName();
console.log(folderName1)
// This sample uses Drive API.
const obj = Drive.Files.get(folderId, {supportsTeamDrives: true});
const folderName2 = obj.title;
console.log(folderName2)
In this sample script, the folder name of the folder is in a shared Drive using Google Apps Script. This script includes 2 patterns. Please confirm it.
In the case of DriveApp, when the file ID and folder ID are used, the files and folders in a shared Drive can be retrieved.
Sample script 2:
When you cannot know the folder ID of the folder in a shared Drive, you can use the following script.
const driveId = "###"; // Please set your Drive ID.
// This sample uses Drive service (DriveApp).
const folders = DriveApp.getFolderById(driveId).getFolders();
while (folders.hasNext()) {
const folder = folders.next();
const folderName1 = folder.getName();
console.log(folderName1)
}
// This sample uses Drive API.
const res = Drive.Files.list({ corpora: "drive", includeItemsFromAllDrives: true, supportsAllDrives: true, driveId, q: `mimeType='${MimeType.FOLDER}' and trashed=false` });
res.items.forEach(({title}) => console.log(title));
In this script, in the case of DriveApp, the folder list is retrieved from just under the top folder of the shared Drive. Please be careful about this.
In the case of Drive API, the folder list of all folders in the shared Drive is retrieved. But, this is a sample script. So, in this case, 100 folders can be retrieved. When you want to retrieve more, please set maxResults and pageToken. Please be careful about this.
Note:
These sample scripts are simple scripts. So, please modify them for your actual situation.
References:
getFolderById(id)
Files: get of Drive API v2
Files: list of Drive API v2
I'm trying to place a copy of a Google Apps Script-file in a shared drive using apps script.
My code looks like this:
function copyFileToSharedDrive(){
var sharedDriveId = "sharedriveidcomeshere";
var sharedDrive = DriveApp.getFolderById(sharedDriveId);
var appsScriptFileId = "appsscriptfileidcomeshere";
DriveApp.getFileById(appsScriptFileId).makeCopy(sharedDrive).setName("This is a copy of the original apps script file");
}
The result, however, is a copy of the apps script file, but it's in my root folder of my Google Drive, instead of in the Shared Drive.
If I do the exact same thing with a Spreadsheet, Google Doc or Slides, the code works like a charm.
I also tried the Advanced Google Services and used the Drive API. No luck there... File is still being created in the root folder of the user executing the code.
Drive.Files.copy(
{title: "This is a copy of the appsscript file", parents: [{id: sharedDriveId}]},
"appsScriptFileId",
{supportsAllDrives: true}
);
Any help?
How about this answer?
Modification points:
Unfortunately, the Google Apps Script file cannot be directly copied to the shared Drive using makeCopy. The file is copied to the root drive of MyDrive. I think that this might be a bug.
So in this case, how about using Drive API? When your script is modified, it becomes as follows.
Modified script:
Before you run the script, please enable Drive API at Advanced Google services.
function copyFileToSharedDrive(){
var sharedDriveId = "sharedriveidcomeshere";
var appsScriptFileId = "appsscriptfileidcomeshere";
Drive.Files.copy(
{title: "This is a copy of the original apps script file", parents: [{id: sharedDriveId}]},
appsScriptFileId,
{supportsAllDrives: true}
);
}
References:
Advanced Google services
Files: copy
Added:
You want to copy a Google Apps Script file to the specifc folder in the shared Drive.
For this, how about the following script? In this script, the following flow is used.
Copy the Google Apps Script file. At this time, the file is created to the root folder.
Move the GAS file to the specific folder in the shared Drive using the Files.patch method of Drive API.
Sample script:
function copyFileToSharedDrive(){
var destinationFolderId = "###"; // Please set the destination folder ID of shared Drive.
var appsScriptFileId = "###"; // Please set the GAS script ID.
var file = DriveApp.getFileById(appsScriptFileId)
var copiedFile = file.makeCopy().setName(file.getName()).getId();
Drive.Files.patch(
{title: "This is a copy of the original apps script file"},
copiedFile,
{removeParents: "root", addParents: destinationFolderId, supportsAllDrives: true}
);
}
Note:
About supportsAllDrives, the official document says as follows.
Deprecated - Whether the requesting application supports both My Drives and shared drives. This parameter will only be effective until June 1, 2020. Afterwards all applications are assumed to support shared drives.
By this, from June 1, 2020, even when supportsAllDrives is not used, the shared Drive can be used.
Reference:
Files: patch
I am having trouble adding files to the shared google drive folder as well as not being able to remove specific types of files of any kind within my script. The shared google drive file gives me issues. The code below works for me on my own personal google drive folder for adding and removing CSV's from one google drive folder to any another that I specify. However, it does not work with our general shared google drive folder. I have been authorized permission via the google cloud console API for Drive & Sheets but I am still having permission issues. Any help or clarification on this issue would be greatly appreciated.
Here are two different pieces of code. The first one with function moveFiles() works on my personal drive but not in the shared folders. Here is also some more code that I was playing around with to test the shared folders in a simpler manner. I was able to get the putFile() function to put a newDoc inside a shared google drive folder but not able to remove it.
function moveFiles(source_folder, dest_folder)
{
// set current destination to grab the folder from
var currentFolder=DriveApp.getFolderById("1emSsRay_WI_z_qBUpQIoccxQID28FvB0");
// grab only the csv's within current folder
var docs = DriveApp.getFilesByType(MimeType.CSV);
// set target destination where we will store old csv's that have been processed & Analyzed
var destination = DriveApp.getFolderById("1wYG1Gd5z0-nucedSMOBn8ZJs68ZgR8Hb");
// iterate through the csv's files within the currentFolder, add them to the destination and remove them from the current folder
while (docs.hasNext())
{
var doc = docs.next();
destination.addFile(doc); // get error "Cannot use this operation on a shared drive item(line 13, file "SharedDriveMove")
currentFolder.removeFile(doc);
}
}
function putFile()
{
var newDoc = DocumentApp.create('Testing Team Drive MoveTo').getId();
var file = DriveApp.getFileById(newDoc);
var moveFile = DriveApp.getFolderById('1emSsRay_WI_z_qBUpQIoccxQID28FvB0').addFile(file);
}
function takeFile()
{
var filesIterator = DriveApp.getFilesByName('Testing Team Drive MoveTo');
while (filesIterator.hasNext())
{
var file = filesIterator.next();
}
var cleanup = DriveApp.getFolderById('1wYG1Gd5z0-nucedSMOBn8ZJs68ZgR8Hb').addFile(file,{"supportsAllDrives": true}); // get error "Cannot find method addFile(File,Object).(line 15,file"Code")
var moveFile = DriveApp.getFolderById('1emSsRay_WI_z_qBUpQIoccxQID28FvB0').removeFile(file,{"supportsAllDrives": true});
}
DriveApp is an Apps Script class whereby it has it's limitations among Drive. Also, as the documentation says:
This method does not delete the file, but if a file is removed from
all of its parents, it cannot be seen in Drive except by searching for
it or using the "All items" view.
You should do it with the Drive API instead:
Use "supportsAllDrives", otherwise it won't find the file if it's in a Shared Drive (until this is deprecated in 2020).
Drive.Files.remove("your file ID", {"supportsAllDrives": true});
You also have to authorize the Drive.File scope.
To share spreadsheets and documents it is easy to write a script:
var sheet = SpreadsheetApp.openById("xxxxxxxxxxxxxxxxxxxxxxxx");
sheet.addViewer("email#gmail.com");
A libray ia a stand alone Google Apps Script file. Is there a comparable script to share such a file?
You can achieve it using DriveApp as follows.
var file = DriveApp.getFileById("xxxxxxxxxxxxxxxxxxxxxxxx");
file.addViewer("email#gmail.com");
If you want to share files as ANYONE, you can use the following sample.
var file = DriveApp.getFileById("xxxxxxxxxxxxxxxxxxxxxxxx");
file.setSharing(DriveApp.Access.ANYONE, DriveApp.Permission.VIEW);
References :
Access
Permission
Using a standalone script, I want to create a new sheet in a given folder.
function criaSheet(){
var folder = DriveApp.getFolderById('ID');
folder.createFile('new Spreadsheet', '', MimeType.GOOGLE_SHEETS)
}
This code asks me to use Google Advanced Services, which one?
And this code creates the sheet in the root folder:
function criaSheet(){
SpreadsheetApp.create('mySheet')
}
You may need to create a new spreadsheet file, then move it to the folder, then delete the original:
function createNewFile(){
var newSS = SpreadsheetApp.create('AAAA11111');
var newID = newSS.getId();
var folder = DriveApp.getFolderById('your folder ID');
var newFile = DriveApp.getFileById(newID);
newFile.makeCopy(folder);
//Delete original file
DriveApp.removeFile(newFile);
};
DriveApp.removeFile() seems to be removing the file without sending it to the trash. Which is fine by me, but Google Drive seems to be doing some weird stuff lately. From the Drive "Details" section, I can open the deleted file, even though there is no trace of it anywhere in any of my folders, including the trash.
If you want to try to figure out the Advanced Drive Service:
In the script editor, choose the Resources menu and Advanced Google Services.
Then turn the Drive API on: