Search code examples
pdfgoogle-apps-scriptgoogle-sheetsgoogle-sheets-macros

How to automate exporting specific sheet (i.e "SheetA") as a PDF to Google Drive?


I create an advanced price calculator and its result located on another sheet called "SheetA". Each time I need to select my printable design area in SheetA and then manually export it as a PDF. I am trying to automate it by macro and when I run the macro it exports SheetA as a pdf to my Google Drive. Could you please help me?


Solution

  • There is a full snippet for export a sheet to another file https://github.com/contributorpw/google-apps-script-snippets/tree/master/snippets/standalone_export-spreadsheet-to

    If you need to export a sheet 'SHEET 1' from the spreadsheet '****' to file you have to

    function runSheet() {
      var spec = ['SHEET 1'];
    
      var spreadsheet = SpreadsheetApp.openById(
        '****'
      ).copy('tmp');
    
      spec.forEach(function(sheetName) {
        var dr = spreadsheet.getSheetByName(sheetName).getDataRange();
        dr.setValues(dr.getValues());
      });
      spreadsheet.getSheets().forEach(function(sheet) {
        if (spec.indexOf(sheet.getName()) < 0) spreadsheet.deleteSheet(sheet);
      });
      var spreadsheetId = spreadsheet.getId();
      var file = exportSpreadsheetToFile_(spreadsheetId, 'xlsx');
      DriveApp.getFileById(spreadsheetId).setTrashed(true);
      return file;
    }
    

    The full listing of exportSpreadsheetToFile_ by the link above.