Jacki Jacki - 7 months ago 19
Java Question

Issue with writing a List into CSV file using CSVWriter

I have the following method to write a list into a CSV file using CSVWriter. Unfortunately, it does not separate them by comma which make them messy when I open it in Excel. How can I modify it?

private void generateCSV(List<String> dataset) throws IOException {
CSVWriter writer = null;
JFileChooser chooser = new JFileChooser();
chooser.setAcceptAllFileFilterUsed(true);
if (chooser.showSaveDialog(chooser) == JFileChooser.APPROVE_OPTION) {
File f = chooser.getSelectedFile();
String file_name = f.toString();
if (!(file_name.endsWith(".csv"))) {
file_name += ".csv";
}
writer = new CSVWriter(new FileWriter(f));
for(int i=0; i< dataset.size(); i++){
String[] str = new String[] {dataset.get(i)};
writer.writeNext(str);
}

} else {
return;
}
writer.close();
}

Answer

You're creating a String[] for each element on your dataset in your for loop and then writing one element per each line with writeNext(). So they are not comma separated because it's just one element per line, using the line separator at the end of each line.

I think that this is what you want. Am I right?

private void generateCSV(List<String> dataset) throws IOException {
    CSVWriter writer = null;
    JFileChooser chooser = new JFileChooser();
    chooser.setAcceptAllFileFilterUsed(true);
    if (chooser.showSaveDialog(chooser) == JFileChooser.APPROVE_OPTION) {
        File f = chooser.getSelectedFile();
        String file_name = f.toString();
        if (!(file_name.endsWith(".csv"))) {
            file_name += ".csv";
        }
        writer = new CSVWriter(new FileWriter(f));
        String[] str = new String[dataset.size()];
        for (int i = 0; i < dataset.size(); i++) {
            str[i] = dataset.get(i);
        }
        writer.writeNext(str);

    } else {
        return;
    }
    writer.close();
}