Search code examples
javacsvgoogle-analytics-apiexport-to-csv

Exporting data in google analytics api to CSV file format using JAVA


Hi all I am in the process of trying to export data that i queried from google analytics api to a csv file format using JAVA. I am very new to java and have looked at using things like supercsv and some other csv converting programs. However I am looking at the code and feel like you can just simply output the data to a csv format. If anyone has suggestions it would be awesome!

private static GaData executeDataQuery(Analytics analytics, String profileId) throws IOException {

    return analytics.data().ga().get("ga:" + profileId, // Table Id. ga: + profile id.
        "today", // Start date.
        "today", // End date.
        "ga:pageviews, ga:visits, ga:uniquePageviews") // Metrics.
        .setDimensions("")
        .setSort("-ga:visits")
        .setFilters("ga:medium==organic")
        .setMaxResults(25)
        .execute();
  }

That is my query

private static void printGaData(GaData results) {
    System.out.println(
        "printing results for profile: " + results.getProfileInfo().getProfileName());

    if (results.getRows() == null || results.getRows().isEmpty()) {
      System.out.println("No results Found.");
    } else {

      // Print column headers.
      for (ColumnHeaders header : results.getColumnHeaders()) {
        System.out.printf("%30s", header.getName());
      }
      System.out.println();

      // Print actual data.
      for (List<String> row : results.getRows()) {
        for (String column : row) {
          System.out.printf("%30s", column);
        }
        System.out.println();
      }

      System.out.println();
    }
  }
}

This is the part that i think i need to modify in order to output it to csv. Thanks all


ok so i have changed it to use buffered writer for the CSV conversion so far i have it so..

public static void main(String[] args) throws IOException{

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));

    BufferedWriter out = new BufferedWriter(new FileWriter("c://data.csv"));
    try {
        String inputLine = null;
        do {
            inputLine=in.readLine();
            out.write(inputLine);
            out.newLine();
        } while (!inputLine.equalsIgnoreCase("eof"));
        System.out.print("Write Successful");
    } catch(IOException e1) {
        System.out.println("Error during reading/writing");
    } finally {
        out.close();
        in.close();
    }
}

for the first part of the writer...

private static void printGaData(GaData results) {

    System.out.println(
        "printing results for profile: " + results.getProfileInfo().getProfileName());

    if (results.getRows() == null || results.getRows().isEmpty()) {
      System.out.println("No results Found.");
    } else {

      // Print column headers.
      for (ColumnHeaders header : results.getColumnHeaders()) {
        pwt.print(header.getName() + ", ");
      }
      pw.println();

      // Print actual data.
      for (List<String> row : results.getRows()) {
        for (String column : row) {
          pw.print(column + ", ");
        }
        pw.println();
      }

      System.out.println();

    }

  }
}

giving me errors saying that it doesnt read it. Anyone wanna give me some pointers? getting errors that says pw cannot be resolved :/


Solution

  • Well where you loop through the columns just add a comma.

    for(String column : row) {
      System.out.println(column + ", ");
    }
    

    You might need to modify it as this code adds a comma at the end of each element, including the last one. You would need to find out if column is the last element of row, and only add a comma if it ISN'T.

    You could connect it to a FileWriter (through BufferedWriter) and output it to a .csv file if you wanted. Put this code at the beginning of your method

    try {
      PrintWriter pw = new PrintWriter(BufferedWriter(new FileWriter("data.csv")));
    }
    catch(Exception e) {
      e.printStackTrace();
    }
    

    and then to print each line your loop would look like this

    for (List<String> row : results.getRows()) {
      for (String column : row) {
        pw.print(row + ",");
      }
      pw.println();
    }
    

    again you would need to find out if column is the last element of row.