简体   繁体   中英

Get total values in google apps script

I'm trying to use "totalsForAllResults" method in google apps script to push out total values for each metrics. I printed out result of each metrics by each dimension to a spreadsheet. And I'd like to see the total values at the end of the row. I tried many times but cat't get it work. I'll be happy if anybody give me advice.

The problem is the last paragraph. This code worked for get analytics data but "totalsForAllResults" doesn't work.

var results = ChannelReportPC(firstProfile); 
   outputToSpreadsheet(results);

function ChannelReportPC(firstProfile) { 

  var profileId = firstProfile.getId();
  var tableId = 'ga:' + profileId;
  var startDate = electiveStartDate('SD');  
  var endDate = electiveEndDate('ED');     

  var optArgs = { 
    'dimensions': 'ga:medium',              // Comma separated list of dimensions.
    'sort': '-ga:sessions',      
    'segment': 'sessions::condition::ga:deviceCategory==desktop,ga:deviceCategory==tablet',  // Process desktop or tablet traffic.
    'start-index': '1',
    'max-results': '20'
  };

  // Make a request to the API.
  var results = Analytics.Data.Ga.get(
      tableId,                    // Table id (format ga:xxxxxx).
      startDate,                  // Start-date (format yyyy-MM-dd).
      endDate,                    // End-date (format yyyy-MM-dd).
    'ga:sessions,ga:percentNewSessions,ga:bounceRate,ga:pageviewsPerSession,ga:avgSessionDuration,ga:transactions,ga:transactionRevenue,ga:transactionsPerSession', // Comma seperated list of metrics.
     optArgs
     );

  var sheet = SpreadsheetApp.getActiveSpreadsheet().insertSheet("media");

}

function outputToSpreadsheet(results) {

  sheet = SpreadsheetApp.getActiveSheet()


  // Print the headers.
  var headerNames = [];
  for (var i = 0, header; header = results.getColumnHeaders()[i]; ++i) {
    headerNames.push(header.getName());
  }
  sheet.getRange(1, 2, 1, headerNames.length)
      .setValues([headerNames])
      .setBackground('#eeeeee');


  // Print the rows of data.
  sheet.getRange(2, 2, results.getRows().length, headerNames.length)
      .setValues(results.getRows());    


  sheet.getRange(getRows().length+1, 2, 1, headerNames.length)
  .setValues(results.totalsForAllResults);
}

I believe your results.totalForAllresults contains array of values. If it is, try to convert it into array of array. Try to follow these steps for your code,

  data = [];
  data.push(results.totalsForAllResults);
  sheet.getRange(getRows().length+1, 2, 1, headerNames.length).setValues(data);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM