google-apps-scriptgoogle-sheets

Copy one sheet from one spreadsheet to another spreadsheet with formatting


I would like to use Google Apps Script to copy a single sheet from a Google spreadsheet into a different Google spreadsheet, and I want to retain formatting (including merged cells). Is there any way to do this? I have tried the following functions:

but these methods only work within the same spreadsheet and do not allow data to be copied between different spreadsheets. Does anyone have any suggestions?


Solution

  • Have you looked here:

    https://developers.google.com/apps-script/reference/spreadsheet/sheet#copyTo(Spreadsheet)

    copyTo(spreadsheet)

    Copies the sheet to another spreadsheet. The destination spreadsheet can be the source. The new spreadsheet will have the name "Copy of [original spreadsheet name]".

     var source = SpreadsheetApp.getActiveSpreadsheet();
    
     var sheet = source.getSheets()[0];
    
     var destination = SpreadsheetApp.openById("ID_GOES HERE");
    
     sheet.copyTo(destination);