google drive API create spreadsheet with custom tabs - google-drive-api

I am creating a spreadsheet using the drive API.
File fileMetadata = new File();
fileMetadata.setName(fileName);
fileMetadata.setParents(Collections.singletonList(folderId));
fileMetadata.setMimeType(MIME_TYPE_SPREADSHEET);
File file = driveService.files().create(fileMetadata)
.setFields("id, parents, name") // properties in the response
.execute();
However this creates a spreadsheet with 1 tab with title "Sheet 1". How can I create a spreadsheet with the drive API with the spreadsheet containing multiple sheets with titles that I would like to provide?

Related

Can I add a script to a Google Sheet using another script?

I have a script populate() to run an automation script on Google Sheets. I want this script to be run on over a hundred Google Sheets files. Is there a way to write a script to add to (or at least run) my populate() script on all those files? I prefer to be able to add the script to each file because we may need to run the scripts multiple times for each file. Otherwise, I will have to manually copy/paste the script to each sheet, which takes time.
Update: Removed the part about converting Excel files to Google Sheets because I found the answer for that on another thread here.
Solution
From what I have understood from your post, your question is about how to convert a series of Excel files inside a Drive folder into Google Sheets to then execute a function in them.
For that, you could iterate over all the files of your folder and convert them with the use of Drive.insert from the Drive API. For that, you will have to enable in your script the Advanced Google Services. If you do not know how to do so, please follow these indications.
The follow script performs what I think you are aiming for, it has self explanatory comments:
function convertExcelToGoogleSheets() {
// Id of the folder where you have all your excel files
var folderId = 'FOLDERID';
var folder = DriveApp.getFolderById(folderId);
// Get all the files in your folder and iterate over them
var files = folder.getFiles();
// For each file:
while (files.hasNext()){
var file = files.next();
// Get its blob (content)
var blob = file.getBlob();
// Create the resource to insert the Google Sheet file. Put the same name
// as the original and set the type of the file to Google sheets and its
// parent folder to where the excel files are located
var resource = {
title: file.getName(),
mimeType: MimeType.GOOGLE_SHEETS,
parents: [{id: folderId}],
};
// User Drive API to insert the actual file and get its ID
var id = Drive.Files.insert(resource, blob).getId();
// Whatever function you want to perform in the newly created Google Sheet
// pasing the parameter of the file id
myScript(id);
}
}
// Set the first cell of all the converted sheets to "IT WORKED"
function myScript(id){
SpreadsheetApp.openById(id).getActiveSheet().getRange('A1').setValue('IT WORKED!');
}
EDIT: If you want to run a script for each of this converted sheets you can simply call it in the while loop and pass the new file id as a parameter to then be able to use the script (remember to encapsulate this script in a function).
I hope this has helped you. Let me know if you need anything else or if you did not understood something. :)

Is there a Google Apps Script that will move the data from a CSV attachment of a GMail email to a defined Google Sheet?

Solution: https://riptutorial.com/google-apps-script/example/20730/get-csv-file-attached-to-a-mail
Google Apps Script Novice trying to set up a script that will run on a time-bound trigger to find the most recent email (will be auto-labeled based on unique sender email) and then auto-transfer the single CSV file's single tab of data to a defined Google Sheet.
Here's a list of how-tos and walkthroughs I've tried:
https://ctrlq.org/code/20279-import-csv-into-google-spreadsheet
Google Apps Script - GMail to Google Sheets - Get Oldest Unread Email in Thread's .csv Attachment
Retrieve csv attachment file from gmail and place the data in a google spreadsheet
How do I convert jpg or png to blob on google app script?
I've watched videos that run through the basics of using Google Apps Scripts on Youtube, signed up for and have completed the first 1/3 of the "Complete Java Certification Course" by Imtiaz Ahmad on Udemy, read through various documentation re Classes and Methods used in Google Apps Scripts and still cannot get this to work. I receive an "TypeError: cannot read property 'length' of undefined...", and it appears my problem stems from the attachment being "undefined".
function test(){
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var data = ss.getRange(1, 1,6,2).getValues();
var threads = GmailApp.search("from:XXXXSENDERSEMAIL#GMAIL.COM");
var message = threads[0].getMessages()[0];
var attachment = message.getAttachments()[0];
var ss1 = SpreadsheetApp.getActive().getUrl();
Logger.log(ss1);
Logger.log(threads);
Logger.log(message);
Logger.log(attachment);
Logger.log(data);
var newarray = attachment[0];
ss.getRange(1, 5, newarray.length, newarray[0].length).setValues(newarray);
}
Expected results: finds the csv attachment, gets data from the csv attachment, writes data on a "Master" spreadsheet that is updated daily (clearvalues/setvalues).
Error message: TypeError: Cannot read property 'getMessages' of undefined (line 30, file "Code")

programatically connect two Spreadsheets so you can IMPORTRANGE without having to manually authorize [duplicate]

This question already has answers here:
How to allow access for importrange function via apps script?
(5 answers)
How can I make an apps script to instantly allow access to all imported elements in a Google Spreadsheet? [duplicate]
(5 answers)
Closed 3 years ago.
First, this is for Enterprise G-Suite. Sharing/publishing outside of work domain is disabled.
This is my setup:
template Spreadsheet in a folder on team drive 1
destination Spreadsheet in a folder on team drive 1
destination folder on a team drive 2
I have a script that:
Copies #1 to #3
Adds an IMPORTRANGE function to #2 that pulls data from the new file created in #3
Now, when I go into #2, I see the import range function there is an error and I have to authorize the sheets: "You need to connect these sheets.". Below is a screenshot:
If I click "Allow access" it works and does pull data from the newly copied file.
What I am wondering is if there is a way to authorize the access programatically in my code so I don't have to open #2 and manually authorize?
var sFileID = "ID of template Spreadsheet in a folder on team drive 1";
var dFileID = "ID destination Spreadsheet in a folder on team drive 1";
var dFolderID = "ID of destination folder on a team drive 2";
// get the 2 files and the folder
var sFile = DriveApp.getFileById(sFileID);
var dFile = DriveApp.getFileById(dFileID);
var dFolder = DriveApp.getFolderById(dFolderID);
// copy the template file to the destination folder
var nFile = sFile.makeCopy("test", dFolder);
// open the destination spreadsheet
var dss = SpreadsheetApp.openById(dFileID);
// get the sheet
var ds = dss.getSheetByName("Sheet1");
// append a new row with the IMPORTRANGE function pulling from the new file
ds.appendRow(['=IMPORTRANGE("' + nFile.getId() + '", "Sheet1!A2:D2")']);
SpreadsheetApp.flush();
There is no way to automatically authorize IMPORTRANGE. Google Apps Script either Google Sheets API have a method that does this.
According to this answer one alternative is to share the source spreadsheet with anyone with the link.
Related
How can I make an apps script to instantly allow access to all imported elements in a Google Spreadsheet?
How to allow access for importrange function via apps script?

How to set where SpreadsheetApp saves spreadsheet?

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)

Create a new Google Sheet in a specific drive folder

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: