在Google Apps脚本中获取总值

时间:2014-11-04 00:52:04

标签: javascript google-apps-script google-analytics-api

我正在尝试在Google Apps脚本中使用“totalsForAllResults”方法来推出每个指标的总值。 我将每个维度的每个指标的结果打印到电子表格中。我希望看到行末的总值。我尝试了很多次但是没有成功。如果有人给我建议,我会很高兴。

问题是最后一段。此代码适用于获取分析数据,但“totalsForAllResults”不起作用。

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);
}

1 个答案:

答案 0 :(得分:0)

我相信您的results.totalForAllresults包含值数组。如果是,请尝试将其转换为数组数组。尝试按照以下步骤操作代码,

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