创建csv文件java

时间:2016-04-27 05:34:41

标签: java google-analytics export-to-csv

我试图将打印方法更改为csv。

    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(); 
        } 
      }

上面的方法打印出三个完美的列。 所以我尝试使用bufferedwriter将这三列写入csv,方法是将代码修改为:

    private static void ExportGaData(GaData results,PrintWriter pw) {


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

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

              pw.close();

            } else {

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

            for (List<String> row : results.getRows()) {
                for (String column : row) {
                  pw.printf("%30s", column,", ");
                    //pw.printf(column + ", ");
                }
                pw.println();

              }

             pw.println();
            }

    }

这会吐出1列而不是3列。日期如下:

columnA's data    columnb's data    columnC's data

所有A列都有很多空格。我如何解决这个问题?

1 个答案:

答案 0 :(得分:1)

我想你想要

for (String column : row) {
       pw.printf(column + ", "); // not row
}