How do I delete a sheet/tab in a Google spreadsheet pragmatically using GAS/Javascript

徘徊边缘 提交于 2020-04-30 08:46:47

问题


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());
        }
    }
}

回答1:


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

First:

Yes, you can replace it.

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

So in your case,

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);

So in your case,

 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. If it has helped, please consider accepting this answer.



来源:https://stackoverflow.com/questions/61303139/how-do-i-delete-a-sheet-tab-in-a-google-spreadsheet-pragmatically-using-gas-java

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!