将API数据输出到csv文件

时间:2015-06-09 13:18:36

标签: google-apps-script

我在这里和各种Google教程上都找到了Frankenstined的代码。我的目标是从Google AnalyticsAPI获取数据并将其输出到我的Google云端硬盘“my_data.csv”中的文件。

我可以在变量“results”中从GA API获取我的数据。结果变量的默认输出是一个对象(我认为?),如下所示:

Logger.log(results);

dataTable={cols=[{id=ga:year, label=ga:year, type=string}, {id=ga:month, label=ga:month, type=string}, {id=ga:medium, label=ga:medium, type=string}, {id=ga:source, label=ga:source, type=string}, {id=ga:campaign, label=ga:campaign, type=string}, {id=ga:goal1Completions, label=ga:goal1Completions, type=number}], rows=[{c=[{v=2015}, {v=06}, {v=(none)}, {v=(direct)}, {v=(not set)}, {v=117}]}, {c=[{v=2015}, {v=06}, {v=(not set)}, {v=(not set)}, {v=(not set)}, {v=0}]}, {c=[{v=2015}, {v=06}, {v=(not set)}, {v=ET}, {v=DL}, {v=0}]}, {c=[{v=2015}, {v=06}, {v=(not set)}, {v=a1e88567-3904-4375-a14a-cff82d7613d2}, {v=wda}, {v=0}]},

或者我可以更改API调用中的输出'output':'dataTable'。结果如下:

Logger.log(results);

rows=[[2015, 06, (none), (direct), (not set), 117], [2015, 06, (not set), (not set), (not set), 0], [2015, 06, (not set), ET, DL, 0], [2015, 06, (not set), a1e88567-3904-4375-a14a-cff82d7613d2, wda, 0], [2015, 06, (not set), google_plus, DL, 0], [2015, 06, Display, Facebook, Facebook, 0], [2015, 06, Display, GOOGLE, ReTargeting, 0], [2015, 06, ET, Email, SearchTopStories, 1], [2015, 06, affiliate, cj, 1651317, 0],

因此我可以通过两种方式输出数据。目前我不知道将我的数据导入csv是哪个“最好”的。现在我正在尝试使用dataTable结构。

这是我的代码:

// set some global vars
var profile = 'ga:XXXXXXXX'; // my actual id added here
var my_csv = 'my_csv';

//trigger function runs everything else
function getToIt() {

    var results = getReportDataForProfile(profile);
    convertRangeToCsvFile_(results, "my_data");
}

// get GA data
function getReportDataForProfile(profile) {

  var startDate = getLastNdays(1);
  var endDate = getLastNdays(0);

  var optArgs = {
    'dimensions': 'ga:year,ga:month,ga:medium,ga:source,ga:campaign', // Comma separated list of dimensions.
    'start-index': '1',
    'max-results': '10',
    'output':'dataTable'
    //'samplingLevel': 'higher-precision'
  };

  // Make a request to the API.
  var results = Analytics.Data.Ga.get( // mcf for multi channel api, Ga for core
      profile,                    // Table id (format ga:xxxxxx).
      startDate,                  // Start-date (format yyyy-MM-dd).
      endDate,                    // End-date (format yyyy-MM-dd).
    'ga:goal1Completions', // Comma seperated list of metrics.
      optArgs);

  Logger.log(results);

  if (results.getRows()) {
    return results;
  }
}

// child function for setting date range
function getLastNdays(nDaysAgo) {
  var today = new Date();
  var before = new Date();
  before.setDate(today.getDate() - nDaysAgo);
  return Utilities.formatDate(before, 'GMT', 'yyyy-MM-dd');
}

// convert results to csv
function convertRangeToCsvFile_(data, file_name) {

  Logger.log("data here:" + data);
  var csv = google.visualization.dataTableToCsv(data);  

  //output to drive
  DriveApp.createFile(file_name, csv);
  return csvFile;
}

我刚刚收到的错误消息是

  

ReferenceError:未定义“google”

看起来我的问题就在这里:

var csv = google.visualization.dataTableToCsv(data); 

如何创建变量csv?鉴于我的环境是GAS,我不确定如何导入google.visualization模块。我甚至不确定这是正确的做法。

1 个答案:

答案 0 :(得分:1)

这是csv转换器的一个非常基本的2d阵列。此外,您无法在服务器端使用JSAPI库,它将无法正常工作。

function arrayToCsv(data){
var csv = ""
var eol = '\r\n';
  for(var i = 0; i<data.length;i++){
     csv += data[i].join();
     csv += eol;
    }
  return csv;
}


function t(){
var data = [[1,2,3],[4,5,6],[7,8,9]];
 data.unshift(["title1","title2","title3"]); // add my header array;
  var newcsv  = arrayToCsv(data);
  Logger.log(newcsv);
  var backToData = Utilities.parseCsv(newcsv);
  Logger.log(backToData);


}