Carlo B.
Carlo B.

Reputation: 119

how to define SpreadsheetApp.getActiveSheet()

I want to have my app script generate output to a SPECIFIC sheet, not the first sheet in the document.

i am looking to do the following:

  1. Have 2 app scripts run on timers for a single google sheet document
  2. App Script 1 will put data into sheet1, named "order_1"
  3. App script 2 will put data into sheet2, named "orders_2"

my code currently puts the output into the active sheet, which is always the first sheet in the document

function import_Completed_orders_FromGmail() {
var threads = GmailApp.search('subject: "orders"');
var message = threads[0].getMessages()[0];
var attachment = message.getAttachments()[0];

// Is the attachment a CSV file
  attachment.setContentTypeFromExtension();  
  if (attachment.getContentType() === "text/csv") {

    var sheet = SpreadsheetApp.getActiveSheet();
    var csvData = Utilities.parseCsv(attachment.getDataAsString(), ",");

    // Remember to clear the content of the sheet before importing new data
    sheet.clearContents().clearFormats();
    sheet.getRange(1, 1, csvData.length, 
csvData[0].length).setValues(csvData);
}
}

is there a way to define "ActiveSheet" by name? or to specify a specific sheet to put this output?

Upvotes: 1

Views: 10864

Answers (2)

Wicket
Wicket

Reputation: 38160

Use getSheetByName(name) method from Class Spreadsheet.

In order to get a Spreadsheet object you will have to use one of the SpreadsheetApp methods to open a spreadsheet like openById(id), open(file), openByUrl(url), getActiveSpreadheet().

Upvotes: 2

Nirav
Nirav

Reputation: 662

You can get both sheet separately and use them in the code.

 var ss = SpreadsheetApp.getActiveSpreadsheet();
 var sheet1 = ss.getSheetByName("order_1");
 var sheet2 = ss.getSheetByName("order_2"); 

Upvotes: 0

Related Questions