我尝试使用带有应用脚本的API从Google Analytics获取数据。 我已经通过每个维度获取每个指标的值,但未显示总值。 在Web视图中,我可以在表格顶部看到每个指标的总值。有没有办法通过API获得这个?
以下是发出请求的代码。
function ChannelReportPC(firstProfile) { //
var profileId = firstProfile.getId();
var tableId = 'ga:' + profileId;
var startDate = electiveStartDate();
var endDate = electiveEndDate();
var optArgs = {
'dimensions': 'ga:medium', // Comma separated list of dimensions.
'sort': '-ga:sessions', // Sort by sessions descending, then keyword.
'segment': 'sessions::condition::ga:deviceCategory==desktop,ga:deviceCategory==tablet', // Process desktop or tablet traffic.
'start-index': '1',
'max-results': '20' // Display the first 250 results.
};
// 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();
if (results.getRows()) {
return results;
} else {
throw new Error('No views (profiles) found');
}
}
以下是在工作表上输出结果的代码。
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, 1, 1, headerNames.length)
.setValues([headerNames])
.setBackground('#eeeeee');
// Print the rows of data.
sheet.getRange(2, 1, results.getRows().length, headerNames.length)
.setValues(results.getRows());
var output = [];
var totals = results.totalsForAllResults;
for (metricName in totals) {
output.push(
'Metric Name = ', metricName, '\n',
'Metric Total = ', totals[metricName], '\n');
}
}