【问题标题】:Create a new spreadsheet with data from just one sheet of another spreadsheet使用仅来自另一个电子表格的一张表的数据创建一个新电子表格
【发布时间】:2021-02-23 15:00:09
【问题描述】:
我有以下代码只打开电子表格的一个选项卡:
const sheetName = SpreadsheetApp.getActiveSheet().getName()
const sheetID = SpreadsheetApp.getActive().getId()
const sheet = SpreadsheetApp.openById(sheetID).getSheetByName(sheetName)
我想从此选项卡中获取数据并创建一个仅包含该数据的新电子表格
【问题讨论】:
标签:
google-apps-script
google-sheets
spreadsheet
【解决方案1】:
解释:
我相信您的目标是通过其 ID 在源电子表格文件(您绑定了脚本的文件)与目标电子表格之间传输数据。
解决办法:
您可以在 cmets 中找到需要调整的说明:
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
}
如果您的目标是即时create 目标电子表格,请使用以下代码:
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
}
参考资料:
openById(id):
打开具有给定 ID 的电子表格。电子表格 ID 可以是
从其 URL 中提取。例如,URL 中的电子表格 ID
https://docs.google.com/spreadsheets/d/abc1234567/edit#gid=0 是
“abc1234567”。
【解决方案2】:
替代方案:
您还可以使用copyTo() 将整个工作表复制到另一个电子表格:
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);
}
参考资料:
copyTo() Spreadsheet