Reputation: 83
I have the following code that opens only one tab of a spreadsheet:
const sheetName = SpreadsheetApp.getActiveSheet().getName()
const sheetID = SpreadsheetApp.getActive().getId()
const sheet = SpreadsheetApp.openById(sheetID).getSheetByName(sheetName)
I would like to take the data from this tab and create a new spreadsheet with just that data
Upvotes: 0
Views: 143
Reputation: 5163
You can also use copyTo()
to copy an entire sheet to another spreadsheet:
function copyTab() {
var source = SpreadsheetApp.getActiveSpreadsheet();
var sheet = source.getActiveSheet();
var destination = SpreadsheetApp.create("New Sheet");
sheet.copyTo(destination);
// optional, this deletes the initial Sheet1 in new spreadsheet
var sheet1 = destination.getSheetByName("Sheet1");
destination.deleteSheet(sheet1);
}
Upvotes: 1
Reputation: 27350
I believe your goal is to transfer data between a source spreadsheet file (the one you have the script bound to) to a target spreadsheet by its id.
In the comments you can find expalanation on what you need to adjust:
function myFunction() {
const source_ss = SpreadsheetApp.getActive();
const target_ss = SpreadsheetApp.openById("id"); // put the id of the target spreadsheet
const source_sheet = source_ss.getSheetByName('Sheet1'); // put the name of the source sheet
const target_sheet = target_ss.getSheetByName('Sheet1'); // put the name of the target sheet
const data = source_sheet.getDataRange().getValues(); // take the data of the source sheet
target_sheet.getRange(1,1,data.length,data[0].length).setValues(data); // paste the data to the target sheet
}
If your goal is to create the target spreadsheet on the fly, then use this code:
function myFunction() {
const source_ss = SpreadsheetApp.getActive();
const target_ss = SpreadsheetApp.create("target"); // create a target spreadsheet
const source_sheet = source_ss.getSheetByName('Sheet1'); // put the name of the source sheet
const target_sheet = target_ss.getSheetByName('Sheet1'); // only this sheet is available in the target sheet
const data = source_sheet.getDataRange().getValues(); // take the data of the source sheet
target_sheet.getRange(1,1,data.length,data[0].length).setValues(data); // paste the data to the target sheet
}
References:
Opens the spreadsheet with the given ID. A spreadsheet ID can be extracted from its URL. For example, the spreadsheet ID in the URL https://docs.google.com/spreadsheets/d/abc1234567/edit#gid=0 is "abc1234567".
Upvotes: 1