如何使用GAS/Javascript实用地删除Google电子表格中的工作表/标签

问题描述:

我有一个代码,可以根据主工作表中的第一行值动态创建新工作表.

I have a code that dynamically creates new sheets based on the first-row value in the main sheet.

我希望有代码来检查工作表名称的存在并覆盖工作表,或者如果存在的话先删除它,然后从主工作表中的新数据重新创建它.

I would like to have the code to check the existence of the sheet name and overwrite the sheet or delete it first if it exists and then creates it afresh from the new data in main sheet.

感谢您在重组中的帮助.

I will appreciate your help in restructuring.

function newSheet() {
    var ss = SpreadsheetApp.getActiveSpreadsheet();
    var templateSheet = ss.getActiveSheet();
    var sheet1 = ss.getSheetByName("main")
    var getNames = [...new Set(sheet1.getRange("A2:A").getValues().filter(String).toString().split(","))];

    for (var i = 0; i < getNames.length; i++) {
        var copy = ss.getSheetByName(getNames[i]);


       if (copy) {  // This is where I am kind lost on how to structure it.

        // if a copy exists delete or overwrite existing sheet here

        } else {

           var rowIndexes = sheet1.getRange("A:A").getValues()
                .map((value, index) => [value[0], (index + 1)])
                .filter(value => value[0] === getNames[i]);


            var namedSheet = ss.insertSheet(getNames[i]);
            rowIndexes.map(index => {
                var rowValues = sheet1.getRange(index[1], 1, 1, sheet1.getLastColumn()).getValues();
                namedSheet.appendRow(rowValues[0]);
            });

            ss.setActiveSheet(ss.getSheetByName(getNames[i]));
            ss.moveActiveSheet(ss.getNumSheets());
        }
    }
}

我认为有多种方法可以实现您正在寻找的解决方案

I think there are multiple ways to achieve the solutions you are looking for

第一:

是的,您可以替换它.

// This example assumes there is a sheet named "first"
var ss = SpreadsheetApp.getActiveSpreadsheet();
var first = ss.getSheetByName("first");
first.setName("not first anymore");

所以在您的情况下,

var copy = ss.getSheetByName(getNames[i]);

if (copy) {  // This is where I am kind lost on how to structure it.

 copy.setName("New name")
 // if a copy exists delete or overwrite existing sheet here

 }

第二: 是的,您也可以删除工作表.

Second: Yes, you can delete the sheet as well.

// The code below deletes the specified sheet.
var ss = SpreadsheetApp.getActive();
var sheet = ss.getSheetByName('My Sheet');
ss.deleteSheet(sheet);

所以在您的情况下,

 if (copy) {  // This is where I am kind lost on how to structure it.

 ss.deleteSheet(copy)
 // if a copy exists delete or overwrite existing sheet here

 }

对不起,如果我误解了您的问题.

Sorry if I have misunderstood your problem.