Skip to content

Instantly share code, notes, and snippets.

@ryanpraski
Forked from chipoglesby/costdata.gs
Last active January 19, 2021 17:03
Show Gist options
  • Save ryanpraski/ea1481768e0b42b826ddd77ecf0eaa61 to your computer and use it in GitHub Desktop.
Save ryanpraski/ea1481768e0b42b826ddd77ecf0eaa61 to your computer and use it in GitHub Desktop.
Cost Data Upload via Google Analytic's Management API with Google Sheets
function uploadData() {
var accountId = "xxxxxxxx";
var webPropertyId = "UA-xxxxxxxx-x";
var customDataSourceId = "xxxxxxxx";
var ss = SpreadsheetApp.getActiveSpreadsheet().getActiveSheet();
var maxRows = ss.getLastRow();
var maxColumns = ss.getLastColumn();
var data = [];
for (var i = 1; i <= maxRows; i++) {
data.push(ss.getRange([i], 1, 1, maxColumns).getValues());
}
var newData = data.join("\n");
var blobData = Utilities.newBlob(newData, "application/octet-stream", "GA import data");
try {
Logger.log(blobData.getDataAsString())
} catch (err) {
Logger.log(err)
}
try {
var upload = Analytics.Management.Uploads.uploadData(accountId, webPropertyId, customDataSourceId, blobData);
SpreadsheetApp.getUi().alert("Uploading: OK");
} catch (err) {
SpreadsheetApp.getUi().alert(err);
}
}
@ryanpraski
Copy link
Author

ryanpraski commented Sep 12, 2016

Here is a full tutorial on how to use this script
In the script editor go to Resources > Advanced Google services...
Turn the Google Analytics API on
In the same overlay window click link to the Google Developers Console
In the Google Developer Console find the Google Analytics API and Enable it

@pbkool
Copy link

pbkool commented Jan 19, 2021

Please note that Logger.log(blobData.getDataAsString()) could throw an error if you try to upload very large files.

I recommend to either remove the Logger.log, or try and catch it.

@ryanpraski
Copy link
Author

thanks for pointing out the potential error @pbkool
I've updated the code to add the try and catch

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment