Open Google Spreadsheet via Google Apps Script after creating a copy - google-apps-script

I am creating a copy of my google spreadsheet, and now want to close the current spreadsheet and open the one i created a copy. I know i can open it using the sheet id, but i dont know the sheet id yet because I want to achieve this using one macro!
current code -
function saveAsSpreadsheet(){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var destFolder = DriveApp.getFolderById("xxxxxxxxxxxxxxxxxxxxx");
DriveApp.getFileById(sheet.getId()).makeCopy("Test File", destFolder);
//want to open this copied file
}

By modified your code a little bit, then you can obtain the copy sheet Id with newsheet.getId() function:
function saveAsSpreadsheet(){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var destFolder = DriveApp.getFolderById("xxxxxV6N-A4Z77f9OijHtAe2VhAU");
var newsheet = DriveApp.getFileById(sheet.getId()).makeCopy("Test File", destFolder);
Logger.log(newsheet.getId())
}

Related

App Script for saving a sheet as PDF to a specific folder

I am looking for an app script that lets me save a sheet as PDF from my Google Workbook to a specific folder in Google Drive based on a condition.
In my Google Drive I have a Google Sheet Workbook file and an employee folder.
The employee folder Id is 1Jy2Yr7u0qrgy90Gvtb6p8V27baS7T_eP
My google workbook has a sheet called 'Sheet2' whose Id is 1DmDBmEijUkolVp7aVgGNK4cTRu5y4uLdzbCrDYO5XRA.
This sheet has a cell C3 that has an employee name. The value in this cell needs to be checked, i.e. if the employee name matches then the script should convert the sheet to a PDF format and place the PDF in employee folder.
I am not a programmer or a coder but doing my best to get this working. I went through many scripts that I found here in stackoverflow and in Youtube and came up with this. I am not sure if it is correct. Need some expert help. Hoping someone can help.
function checkSheet() {
var sheetName = "1DmDBmEijUkolVp7aVgGNK4cTRu5y4uLdzbCrDYO5XRA";
var folderID = "1Jy2Yr7u0qrgy90Gvtb6p8V27baS7T_eP";
var sourceSpreadsheet = SpreadsheetApp.getActive();
var sourceSheet = sourceSpreadsheet.getSheetByName(sheetName);
var folder = DriveApp.getFolderById(folderID);
var checkForNews = spreadsheetApp.getActiveSpreadsheet().getSheetByName("Tracking").getRange("c6").getValue();
if (checkForNews='Yes') {
var destSpreadsheet = SpreadsheetApp.open(DriveApp.getFileById(sourceSpreadsheet.getId()).makeCopy("tmp_convert_to_pdf", folder));
var theBlob = destSpreadsheet.getBlob().getAs('application/pdf').setName(pdfName);
var newFile = folder.createFile(theBlob);
}
}
Here are the resource that I found,
Using Google Apps Script to save a single sheet from a spreadsheet as pdf in a specific folder
How to check for cell value?
How can I modify this to save a spreadsheet into a new folder
As mentioned above I came up with that script which I think is not right. Please help.
Try it this way:
function checkSheet() {
const ss = SpreadsheetApp.getActive();
const sh = ss.getSheetByName("Tracking");
var fldr = DriveApp.getFolderById("folder id");
if(sh.getRange("C6").getValue() == "Yes") {
var theBlob = ss.getBlob().getAs('application/pdf').setName("mypdf");
fldr.createFile(theBlob);
}
}

Google Apps Script, Google Sheets - Getting Spreadsheet ID and Sheet ID programmatically

I've been reading this without making any headway:
https://developers.google.com/apps-script/reference/spreadsheet/spreadsheet-app
Is there a way to programmatically get the Spreadsheet ID and Sheet ID of a particular Google SpreadSheet's sheet without manually typing or copying the URL?
1.) If the script is bound to the spreadsheet then you can just use getID and getSheetID as mentioned by TheMaster in the comments. See codes below:
function getIDs() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
var spreadSheetID = ss.getId();
var sheetID = sheet.getSheetId();
console.log(spreadSheetID);
console.log(sheetID);
}
Result:
Take note that the first sheet always has an ID of 0 (gid=0) as the default value.
2.) Otherwise if what you are trying to do is get the Spreadsheet ID and Sheet ID from different spreadsheets it is not possible without copying the URL since there is no way it can identify which spreadsheet to refer to.
3.) Suggestion
What you can do if you need to get IDs of different files is to move them to a folder in your drive, then you can use the code below:
function listFilesInFolder(folderName) {
var sheet = SpreadsheetApp.getActiveSheet();
sheet.getRange(1,1,sheet.getLastRow(),sheet.getLastColumn()).clearContent();
sheet.appendRow(["Name", "Spreadsheet ID", "Sheet ID"]);
//change the folder ID below to reflect your folder's ID (look in the URL when you're in your folder)
var folder = DriveApp.getFolderById("HIS_SHOULD_BE_YOUR_FOLDER_ID");
var contents = folder.getFiles();
var cnt = 0;
var file;
while (contents.hasNext()) {
var file = contents.next();
cnt++;
data = [
file.getName(),
file.getId(),
];
var spreadsheetSheets = SpreadsheetApp.openById(data[1]).getSheetByName("Sheet2").getSheetId();
data.push(spreadsheetSheets);
sheet.appendRow(data);
};
};
Folder:
Result:
Note: In my example code I've made use of Sheet2 to see that it is working as expected. Please set accordingly to the name of the sheet which you are trying to get the ID.
Let me know if this works for you or if you have other questions.
References:
Are Google Spreadsheets' first sheets always given an ID of 0?
Getting all files ID in drive folder

How to copy one google sheet to different another google sheet

I do have two different google sheet, I need to copy say sheet Test from one to another using script, but getting error, any thought on this?
var source_sheet= "https://address of the otgoogle sheet tho be copied over")"
//here I'm on another google sheet, add a menu to copy the source from above
var ui = SpreadsheetApp.getUi();
//var ss = SpreadsheetApp.getActiveSpreadsheet();
var result = ui.prompt(
'Add New Sheet',
'Please enter Name',
ui.ButtonSet.OK);
var button = result.getSelectedButton();
var text = result.getResponseText();
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getActiveSheet();
sheet.copyTo(link_to_src).setName(text);
Getting below error:
Exception: The parameters (String) don't match the method signature for SpreadsheetApp.Sheet.copyTo. (line xx, file "copy-rename")DetailsDismiss
Any help will be appreciated in advance..
You want to copy a sheet of the source Spreadsheet, which is not the active Spreadsheet to the active Spreadsheet, which run the script.
source_sheet is the URL of Spreadsheet like https://docs.google.com/spreadsheets/d/{spreadsheetId}/edit.
When you run the script, you want to input the sheet name in source Spreadsheet using a dialog and copy the sheet to the active Spreadsheet.
I could understand like above. If my understanding is correct, how about this modification?
Modified script
Please modify your script as follows. Before you run the script, please set the destination Spreadsheet URL to source_sheet.
From:
var sheet = ss.getActiveSheet();
sheet.copyTo(link_to_src).setName(text);
To:
var sourceSheet = SpreadsheetApp.openByUrl(source_sheet).getSheetByName(text);
if (sourceSheet) {
sourceSheet.copyTo(ss).setName(text).activate();
} else {
ui.alert(text + " sheet was not found.");
}
When you run the script, a dialog is opened. When a sheet name of the source Spreadsheet is inputted, the sheet is copied to the current active Spreadsheet, then, the copied sheet is activated.
If the sheet name which is not included in the source Spreadsheet is inputted, a dialog is opened.
References:
openByUrl(url)
copyTo(spreadsheet)

Copying / transferring from one spreadsheet to another code based

I'm trying to copy / transfer a sheet from one spreadsheet to another spreadsheet. I have tried various methods and .copyTo seems to be the best and most efficient way.
.copyTo works well but I'm struggling to send to a specific sheet...
Here is my code:
function TransferDataOut() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheetA = source.getSheets()[0]; //sheet source number
var destination = SpreadsheetApp.openById('the destination sheet');
var each = "Data_Incoming";
var ss = SpreadsheetApp.getActiveSpreadsheet();
sheetA.copyTo(destination); // I tried renaming .setName(each);
}
So if I only use sheetA.copyTo(destination); it simply creates a copy sheet, like Copy of the_souce_sheet_name.
If I try renaming to make it a specific name I will get error after running for the second time that the sheet already exists in destination spreadsheet.
What I really need to achieve is that the function from source spreadsheet copies data from the source sheet to always the same sheet in destination spreadsheet.
Perhaps .copyTo is not the right way to do it?
Any suggestions and code will help please!
The reason for receiving data on a exact sheet in the destination spreadsheet is because I have a trigger On change that executes another script to work with the new incoming data.
You want to overwrite the source sheet of Spreadsheet A to the destination sheet of Spreadsheet B.
You want to keep the sheet name of var each = "Data_Incoming".
If my understanding is correct, how about this answer? I would like to propose 2 samples. So please select one of them for your situation.
Sample script 1:
The flow of this sample script is as follows.
each sheet of Spreadsheet B is deleted.
Source sheet of Spreadsheet A is copied to the destination sheet of Spreadsheet B.
Sheet name of the copied sheet of Spreadsheet B is modified to each.
Modified script:
function TransferDataOut() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheetA = source.getSheets()[0]; //sheet source number
var destination = SpreadsheetApp.openById('the destination sheet');
var each = "Data_Incoming";
var destSheet = destination.getSheetByName(each);
if (destSheet) {
destination.deleteSheet(destSheet);
}
sheetA.copyTo(destination).setName(each);
}
Sample script 2:
The flow of this sample script is as follows.
Copy the source sheet of Spreadsheet A to Spreadsheet B.
If the sheet with the sheet name of each is not existing in Spreadsheet B, the copied sheet is renamed to each.
If the sheet with the sheet name of each is existing in Spreadsheet B, the source sheet is copied to the Spreadsheet B as Copy of ###.
each sheet is cleared.
All values, formulas and formats of the copied sheet are copied to each sheet.
Delete the copied sheet.
Modified script:
function TransferDataOut() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheetA = source.getSheets()[0]; //sheet source number
var destination = SpreadsheetApp.openById('the destination sheet');
var each = "Data_Incoming";
var copiedSheet = sheetA.copyTo(destination);
var destSheet = destination.getSheetByName(each);
if (destSheet) {
destSheet.clear();
var srcRange = copiedSheet.getDataRange();
srcRange.copyTo(destSheet.getRange(srcRange.getA1Notation()));
destination.deleteSheet(copiedSheet);
} else {
copiedSheet.setName(each);
}
}
Note:
In this sample script, each sheet of the Spreadsheet B (destination Spreadsheet) is deleted. So please be careful this.
So at first, as a test, I recommend to use a sample Spreadsheet.
References:
copyTo(spreadsheet) of Class Sheet
copyTo(destination) of Class Range
deleteSheet(sheet)
If I misunderstood your question and this was not the result you want, I apologize.
Added:
You want to run the script of destination Spreadsheet when the source values are copied to the destination Spreadsheet using the script in the source Spreadsheet.
The following sample script is for achieving above situation.
Script of destination Spreadsheet:
At first, the script of destination Spreadsheet is prepared.
Script:
function doGet() {
sample(); // This is the function that you want to run when the source values are copied.
return ContentService.createTextOutput();
}
After copy and paste above script to the script editor of destination Spreadsheet, please do the following flow.
Deploy Web Apps.
On the script editor, Open a dialog box by "Publish" -> "Deploy as web app".
Select "Me" for "Execute the app as:".
Select "Anyone, even anonymous" for "Who has access to the app:".
Click "Deploy" button as new "Project version".
Automatically open a dialog box of "Authorization required".
Click "Review Permissions".
Select own account.
Click "Advanced" at "This app isn't verified".
Click "Go to ### project name ###(unsafe)"
Click "Allow" button.
Copy "Current web app URL:".
It's like https://script.google.com/macros/s/#####/exec.
Click "OK".
Script of source Spreadsheet:
As the next step, the script of source Spreadsheet is prepared as follows. In this sample, the sample 2 was used. I think that you can also use the sample 1.
Script:
function TransferDataOut() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheetA = source.getSheets()[0]; //sheet source number
var destination = SpreadsheetApp.openById('the destination sheet');
var each = "Data_Incoming";
var copiedSheet = sheetA.copyTo(destination);
var destSheet = destination.getSheetByName(each);
if (destSheet) {
destSheet.clear();
var srcRange = copiedSheet.getDataRange();
srcRange.copyTo(destSheet.getRange(srcRange.getA1Notation()));
destination.deleteSheet(copiedSheet);
} else {
copiedSheet.setName(each);
}
// Added
var url = "https://script.google.com/macros/s/###/exec"; // Please set the retrieved URL of Web Apps.
UrlFetchApp.fetch(url);
}
Note:
By above settings, when TransferDataOut() of the source Spreadsheet was run, doGet() of the destination Spreadsheet is run by UrlFetchApp.fetch(url).
References:
Web Apps
Taking advantage of Web Apps with Google Apps Script

Create template Google Sheet with script to rename from cell value

I am trying to create a Google Sheet template where a user can enter a value (Project URN) in a cell and run a script to save the template as a sheet, renamed with the Project URN.
I have created a test Google Sheet here https://docs.google.com/spreadsheets/d/1IPpQyYHl_TtNa1lGpmu4dlzwTFjOotV2OcnxFT84iUk/edit?usp=sharing
This sheet has the following script, but I cant get the renaming function to correctly work.
function saveAsSpreadsheet(){
var sheet = SpreadsheetApp.getActiveSpreadsheet();
var destFolder = DriveApp.getFolderById("0B7RrbZuJGLlha3NvM3ZqcTY3MDA");
DriveApp.getFileById(sheet.getId())
.(makeCopy(values = SpreadsheetApp.getActiveSheet()
.getRange(2, 2).getValues()), destFolder);
} //END function saveAsSpreadsheet
I did also find the following article but wasn't able to turn it to my use. However, the secret must be here somewhere! Rename worksheet to cell value keeping format
Kitten
You almost have it. Please try this:
function myFunction() {
var ss = SpreadsheetApp.getActiveSpreadsheet(); // Get spreadsheet
var id = ss.getId(); // Get spreadsheet ID
var sstocopy = DriveApp.getFileById(id); //Get spreadsheet with DriveApp
var sheet = ss.getActiveSheet(); // Grab the sheet in order to find the name of the new spreadsheet to be created
var sheet_name = sheet.getRange("A1").getValue(); // Get the value, in this case: Project Urn
var folder = DriveApp.getFolderById("XXXX"); // Get the folder where the sheet needs to be placed.
sstocopy.makeCopy(sheet_name,folder); // Make the copy of the sheet in that folder.
}
Let me know if you have any questions.