2

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

1 Answer 1

1

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();
}
Sign up to request clarification or add additional context in comments.

5 Comments

Yes Exactly .. Thank you so much ... Appreciate your explanation
We I open it as Excel, it is not really distributed since they are supposed to be in 34 columns and 321 rows. Do you see why ? Also it is surrounded by "", is there a way to remove it ?
Try to put sep=, as first line in your .csv file, and then open with Excel.
To remove "" change writer.writeNext(str); to writer.writeNext(str, false);. I think it should work.
Check this superuser post for more options related with open CSV with commas in Excel.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.