如何使用Google SpreadSheet将费用上传到Google Analytics

时间:2016-04-18 19:29:16

标签: csv google-apps-script google-analytics google-sheets google-spreadsheet-api

我知道可以通过web interface将数据费用上传到Google Analytics。但是,我想让这个过程更加自动化,所以我考虑使用谷歌电子表格和谷歌应用程序脚本来缩短这个过程。

我的想法是在spreadSheet上获取我要上传到Google Analytics的数据,然后使用Google Apps脚本高级服务将数据费用上传到我的Google Analytics(分析)财产。遗憾的是,Google App Script Advanced Services上的文档非常有限。所以我跳了一些人可以帮助我。这是迄今为止所做的:

**@BeforeClass
        public static void testSetup() throws InterruptedException, IOException, APIException {
            initTestRail();
        }
@AfterMethod
public void getStatusAndAnnotation(ITestResult result) throws NoSuchMethodException, IOException, APIException {
    HashMap<Object, Object> map = new HashMap<>();
    Method m = getClass().getMethod(result.getName());
    TestCase annotation = m.getAnnotation(TestCase.class);
    try {
        map.put("testRailCaseId",annotation.testRailCaseId());
    }catch (NullPointerException e){}
    if (result.isSuccess()) {
        map.put("result", 1);
    } else {
        map.put("result", 5);
    }
    if(annotation.testRailDeployEnable() && !map.get("testRailCaseId").equals(null) && !map.get("testRailCaseId").toString().isEmpty())
    {
        TestRailIntegration.addTestResult(map);
    }
    else System.out.println("Deploying result was canceled, because test has annotation \"testRailDeployEnable: false\" or \"testRailCaseId\" has no value");
}**

我找到了一个转换range to a CSV as a string的代码。但我不知道如何获取此字符串并将其转换为blob,因此我可以将其用作方法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); } 中的mediaData参数。

我相信调用这个方法可以解决问题,但是我不知道如何传递mediaData参数中的数据,正如我所说,我找不到任何解释这种方法是如何工作的文档。我知道mediaData应该是Blob类型,但我找不到任何解释如何创建一个CSV文件的Blob的例子。

1 个答案:

答案 0 :(得分:6)

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