我有一个包含三列员工信息的表。第一列有雇员姓名。我想写一个谷歌应用程序脚本,它将复制预先格式化的模板表,并使用员工名称重新命名。在脚本结束时,每个员工都将拥有自己的工作表。
以下是我到目前为止的代码,我正在使用Google脚本教程中的一些功能,但我对如何继续进行操作感到茫然。编辑,我已经进一步了,这段代码工作了一次,但现在挂起了setName:
//Create new sheets for each employee in the list
function createEmployeeSheets() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var sheet = ss.getSheets()[0];
// Get the range of cells that store employee data.
var employeeDataRange = ss.getRangeByName("EmployeeRef");
// For every row of employee data, generate an employee object.
var employeeObjects = getRowsData(sheet, employeeDataRange);
for (i=0; i < employeeObjects.length; i++) {
var EmployeeName = employeeObjects[i].name;
ss.setActiveSheet(ss.getSheetByName("Template"));
SpreadsheetApp.getActiveSpreadsheet().duplicateActiveSheet();
var first = ss.getSheetByName("Copy of Template 1");
first.setName(EmployeeName);
}
}
答案 0 :(得分:1)
在参观了这个Q&amp; A后,我找到了一个更简单的方法:
function createEmployeeSheets() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
// Get the range of cells that store employee data.
var employeeDataRange = ss.getRangeByName("EmployeeRef");
var employeeObjects = employeeDataRange.getValues();
var template = ss.getSheetByName('Template');
for (var i=0; i < employeeObjects.length; i++) {
// Put the sheet you want to create in a variable
var sheet = ss.getSheetByName(employeeObjects[i]);
// Check if the sheet you want to create already exists. If so,
// log this and loop back. If not, create the new sheet.
if (sheet) {
Logger.log("Sheet " + employeeObjects[i] + "already exists");
} else {
template.copyTo(ss).setName(employeeObjects[i]);
}
}
return;
}
答案 1 :(得分:0)
使用copyTo()
功能可以更简单。
另外,请确保您拥有唯一的EmployeeNames。
所以你的代码看起来像是:
function test() {
var ss = SpreadsheetApp.getActiveSpreadsheet();
var employeeObjects = [
{"name": "Peter" },
{"name": "Alice" },
{"name": "Frank" }
]
var template = ss.getSheetByName('Template');
for ( var i=0; i < employeeObjects.length; i++) {
var EmployeeName = employeeObjects[i].name;
// get the sheets to check you are not creating a duplicate sheet
var sheets = ss.getSheets();
var ok = true;
// loop through the sheets and check a duplicate exist
for ( var j=0; j<sheets.length;j++ ) {
if ( sheets[j].getName() == EmployeeName ) {
ok = false;
Logger.log('duplicate');
}
}
if ( ok ) {
template.copyTo(ss).setName(EmployeeName);
} else {
// do whatever you need to do if employee name is duplicate
}
}
}