How to upload cost to Google Analytics using Google SpreadSheet

断了今生、忘了曾经 提交于 2020-01-02 15:45:31

问题


I know it is possible to upload data cost to Google Analytics via the web interface. I, however, want to make this process a bit more automatic, so I thought about using google spreadsheet and google app script to short this processes.

My ideia is to get the data I want to upload to Google Analytics on a spreadSheet and then use Google Apps Script Advanced Services to upload the data cost to my google Analytics Property. Unfortunately the documentation on Google App Script Advanced Services is very limited. So I was hopping some one could help me. Here is what´ve done so far:

function uploadDataCost() {

  var accountId = "XXXXXXXX";
  var webPropertyId = "UA-XXXXXXX";
  var customDataSourceId = "XXXXXXXXXXXXX";

  var csvData = convertRangeToCSVString();      

  var mediaData = Utilities.newBlob([]); //This variable is my main problem.

  Analytics.Management.Uploads.uploadData(accountId, webPropertyId, customDataSourceId, mediaData);



}

I have found a code that converts the range to a CSV as a string. But I don´t know how to take this string and convert it to a blob so I can use it as the mediaData parameter in the method Analytics.Management.Uploads.uploadData(accountId, webPropertyId, customDataSourceId, mediaData);.

I believe calling this method would do the trick, however I´m not sure how to pass the data in the mediaData parameter and as I said, I could not find any documentation explaining how this method works. I know that mediaData should be of Blob type, but I could not find any examples explaining how to create a Blob that is a CSV file.


回答1:


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 {
    var upload = Analytics.Management.Uploads.uploadData(accountId, webPropertyId, customDataSourceId, blobData);
    SpreadsheetApp.getUi().alert("Uploading: OK");
  }
  catch(err) {
    SpreadsheetApp.getUi().alert("Cannot upload: Failed");
  }
}

Source



来源:https://stackoverflow.com/questions/36702745/how-to-upload-cost-to-google-analytics-using-google-spreadsheet

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!