Home > Mobile >  Export two pages of a spreedsheet
Export two pages of a spreedsheet

Time:02-11

I want export two pages of a same spreedsheet to one single file, how can i do it?

  var ssID = "ssID"  
  var url = "https://docs.google.com/spreadsheets/d/" ssID "/export?format=xlsx&gid=AAAA";
  var url2 = "https://docs.google.com/spreadsheets/d/" ssID "/export?format=xlsx&gid=BBBB";
  var params = {method:"GET", headers:{"authorization":"Bearer "  ScriptApp.getOAuthToken()}};
  var response = UrlFetchApp.fetch(url, params);
  DriveApp.createFile(response).setName(name);

CodePudding user response:

I believe your goal is as follows.

  • You want to select 2 of all sheets in a Google Spreadsheet and export it as one XLSX file using Google Apps Script.

In this case, how about the following sample script?

Sample script:

function myFunction() {
  var name = "sample.xlsx"; // Please set the output filename.
  var ssID = "###"; // Please set your Spreadsheet ID.
  var sheetIds = [12345, 67890]; // Please set the sheet IDs.
  
  // 1. Create new Spreadsheet as a temporal.
  var temp = SpreadsheetApp.create("temp");
  var tempId = temp.getId();
  
  // 2. Copy the selected sheets to the temp Spreadsheet.
  SpreadsheetApp.openById(ssID).getSheets().filter(s => sheetIds.includes(s.getSheetId())).forEach(s => s.copyTo(temp).setName(s.getSheetName()));
  temp.deleteSheet(temp.getSheets()[0]);
  
  // 3. Export the temp Spreadsheet as a XLSX file.
  var url = "https://docs.google.com/spreadsheets/d/"   tempId   "/export?format=xlsx";
  var params = { method: "GET", headers: { "authorization": "Bearer "   ScriptApp.getOAuthToken() } };
  var response = UrlFetchApp.fetch(url, params);
  DriveApp.createFile(response).setName(name);

  // 4. Remove the temp Spreadsheet.
  DriveApp.getFileById(tempId).setTrashed(true);
}

References:

  • Related