Java CSV写作

时间:2016-11-23 16:03:23

标签: java excel csv

我目前正在尝试将数据写入excel以获取报告。我可以将数据写入csv文件,但它不按我想要的顺序出现在excel中。我需要在每列的最佳和最差适应度下打印数据,而不是全部打印在平均值下。以下是相关代码,任何帮助将不胜感激:

    String [] Fitness = "Average fitness#Worst fitness #Best Fitness".split("#");
    writer.writeNext(Fitness);

    //takes data from average fitness and stores as an int
    int aFit = myPop.individuals[25].getFitness();
    //converts int to string
    String aFit1 = Integer.toString(aFit);
    //converts string to string array
    String aFit2 [] = aFit1.split(" ");
    //writes to csv
    writer.writeNext(aFit2);
    //String [] nextCol = "#".split("#");



    int wFit = myPop.individuals[49].getFitness();
    String wFit1 = Integer.toString(wFit);
    String wFit2 [] = wFit1.split(" ");
    writer.writeNext(wFit2);

    int bFit = myPop.individuals[1].getFitness();
    String bFit1 = Integer.toString(bFit);
    String bFit2 [] = bFit1.split(" ");
    writer.writeNext(bFit2);

enter image description here

4 个答案:

答案 0 :(得分:0)

来自文档 CSVWriter.html#writeNext(java.lang.String[])

public void writeNext(String[] nextLine) - 将下一行写入文件。

要提供的String数组是

  

一个字符串数组,每个逗号分隔的元素作为单独的条目。

您正在编写3个单独的行而不是1,并且您编写的每一行都包含一个带有单个条目的数组。

writer.writeNext(aFit2);
writer.writeNext(wFit2);
writer.writeNext(bFit2);

<强>解决方案: 创建一个包含所有3个条目(列值)的数组,并在一行中写入一次。

答案 1 :(得分:0)

我认为你应该打电话给你的#34; writeNext&#34;每行数据一次方法:

String [] Fitness = "Average fitness#Worst fitness #Best Fitness".split("#");
writer.writeNext(Fitness);

int aFit = myPop.individuals[25].getFitness();
String aFit1 = Integer.toString(aFit);

int wFit = myPop.individuals[49].getFitness();
String wFit1 = Integer.toString(wFit);

int bFit = myPop.individuals[1].getFitness();
String bFit1 = Integer.toString(bFit);

writer.writeNext(new String[]{aFit1, wFit1, bFit1});

答案 2 :(得分:0)

我假设您正在使用CSVWriter写入CSV文件。请确保在问题中尽可能多地提及细节,这使得其他人更容易阅读。

从CSVWriter的文档中可以看到:

  

void writeNext(String [] nextLine)

     

将下一行写入文件。

writeNext方法实际上将数组写入文件的单独一行。从你的代码:

writer.writeNext(aFit2);
writer.writeNext(wFit2);
writer.writeNext(bFit2);

所以,不要这样做`String aFit2 [] = aFit1.split(“”); 创建值的数组,然后将该数组传递给 writeNext

举个例子,您可以考虑自己传递列名数组的示例,这些列名称写在一行中:

writer.writeNext(Fitness);

答案 3 :(得分:0)

Apache Commons CSV

这里是相同的解决方案,但使用的是Apache Commons CSV库。该库专门支持CSV格式的Microsoft Excel变体,因此您可能会发现它特别有用。

在此示例中,您的数据(已读写)。

Screenshot of seven rows of plain data in a CSV file, with three columns: Average, Worst, Best.

Common CSV库可以读取第一行作为标题名称。

这是单个.java文件中的完整示例应用程序。首先,应用程序从现有的WorstBest.csv数据文件中进行读取:

Average,Worst,Best
10,5,15
11,5,16
10,6,16
11,6,15
10,5,16
10,5,16
10,4,16

每行表示为三个List对象(String)中的List< String >。我们将每一行添加到集合,列表列表,List< List< String > >

然后我们将导入的数据写到另一个文件中。每个书面文件的名称均为WorstBest_xxx.csv,其中xxx是UTC的当前时刻。

package com.basilbourque.example;

import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVPrinter;
import org.apache.commons.csv.CSVRecord;

import java.io.BufferedReader;
import java.io.IOException;
import java.nio.charset.StandardCharsets;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.time.Instant;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.Objects;

public class WorstBest {
    public static void main ( String[] args ) {
        WorstBest app = new WorstBest();
        List < List < String > > data = app.read();
        app.write( data );
    }

    private List < List < String > > read ( ) {
        List < List < String > > listOfListsOfStrings = List.of();
        try {
            // Locate file to import and parse.
            Path path = Paths.get( "/Users/basilbourque/WorstBest.csv" );
            if ( Files.notExists( path ) ) {
                System.out.println( "ERROR - no file found for path: " + path + ". Message # 3cf416de-c33b-4c39-8507-5fbb72e113f2." );
            }

            // Hold data read from file.
            int initialCapacity = ( int ) Files.lines( path ).count();
            listOfListsOfStrings = new ArrayList <>( initialCapacity );

            // Read CSV file.
            BufferedReader reader = Files.newBufferedReader( path );
            Iterable < CSVRecord > records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse( reader );
            for ( CSVRecord record : records ) {
                // Average,Worst,Best
                // 10,5,15
                // 11,5,16
                String average = record.get( "Average" ); // Must use annoying zero-based index counting.
                String worst = record.get( "Worst" );
                String best = record.get( "Best" );

                // Collect
                listOfListsOfStrings.add( List.of( average , worst , best ) ); // For real work, you would define a class to hold these values. 
            }

        } catch ( IOException e ) {
            e.printStackTrace();
        }
        return listOfListsOfStrings;
    }

    private void write ( List < List < String > > listOfListsOfStrings ) {
        Objects.requireNonNull( listOfListsOfStrings );
        // Determine file in which to write data.
        String when = Instant.now().truncatedTo( ChronoUnit.SECONDS ).toString().replace( ":" , "•" ); // Colons are forbidden in names by some file systems such as HFS+.
        Path path = Paths.get( "/Users/basilbourque/WorstBest_" + when + ".csv" );
        // Loop collection of data (a list of lists of strings).
        try ( final CSVPrinter printer = CSVFormat.EXCEL.withHeader( "Average" , "Worst" , "Best" ).print( path , StandardCharsets.UTF_8 ) ; ) {
            for ( List < String > list : listOfListsOfStrings ) {
                printer.printRecord( list.get( 1 - 1 ) , list.get( 2 - 1 ) , list.get( 3 - 1 ) );  // Annoying zero-based index counting.
            }
        } catch ( IOException e ) {
            e.printStackTrace();
        }
    }
}