Search code examples
javacsvopencsv

How to create new column from CSVWriter in Java


I have a problem. I want to create a new CSV file from CSVWriter and my whole Array is set into the one cell.

This is my java code:

StringWriter s = new StringWriter();
        @SuppressWarnings("deprecation")
        CSVWriter writer = new CSVWriter(s, '\t');

        String[] entries = new String[3];
        entries[0] = "Test";
        entries[1] = "Test";
        writer.writeNext(entries);

        writer.close();
        String finalString = s.toString();
        System.out.println(finalString);

I get the output like this: "first" "second" "third" and my CSV is : enter image description here but I want to be like this: enter image description here


Solution

  • Your code is OK, the problem is you open the CSV file by Excel with default settings.

    If you open the CSV file with Notepad, it will look like this:

    "Test" "Test"

    And if you still want to open it with Excel, you are supposed to open it by following steps:

    1. Create a new sheet.
    2. Select Data > From Text File.
    3. Select file (write.csv) to be imported.
    4. Click Finish.