2016-04-27 19 views
1

代わりに印刷方法をcsvに変更しようとしています。create csv file java

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

この方法では、3つの列が完全に印刷されます。 だから私はにコードを変更することで、CSVにそれらの3つの列を記述するためにBufferedWriterのを使用しよう:

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 

はすべてspaces.Howの多くが付いている欄Aに私はこれを解決するのですか?

答えて

1

は、私はあなたが

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

ええ、私はちょうどそれを実現したいと思うが、私は列にそれを変更した後、CSVは空だった、私は一つの列(列A)で3個の列のデータを得た後、コードを変更しましたスペース。私は3つの列にどのように解析するのですか? – Sailormoon

+0

pw.printf(column、 "、")pw.printf( "%30s"、column、 "、")を使用して、 3列全て – Sailormoon

+0

あなたはあなたのプリントライターを閉じる必要があります –