CSVPrinter datas appears not separated in columns

吃可爱长大的小学妹 提交于 2021-01-07 05:07:33

问题


I'm trying to use this library commons-csv (1.5) for generating the csv file, i've make a simple program for seeing the result :

String SAMPLE_CSV_FILE = "./sample.csv";

        try (
            BufferedWriter writer = Files.newBufferedWriter(Paths.get(SAMPLE_CSV_FILE));
            CSVPrinter csvPrinter = new CSVPrinter(writer, CSVFormat.EXCEL
                    .withHeader("ID", "Name", "Designation", "Company"));
        ) {
            csvPrinter.printRecord("1", "Name1 ", "CEO", "Google");
            csvPrinter.printRecord("2", "Name2", "CEO", "Microsoft");

            csvPrinter.flush();            
        }

My CSV is well generated but the header and the data isnt separated in each column, When I open the CSV file, I see all the data and header in the first column

I dont found yet the good CSVFormat, how to separate them ?


回答1:


When I run your program, I get all the columns separated by comma's as expected. If you're using Excel to open the file, make sure you have selected the comma as the delimiter instead of the tab.




回答2:


The selected answer does not really show how you can make sure that comma is set as the delimiter.

To tell excel that comma should be used as a delimiter, Print printer.printRecord("SEP=,"); as the first record in your file. its a command that excel understands and it will not show in your file output.

try (CSVPrinter printer = new CSVPrinter(new FileWriter("file.csv"),CSVFormat.EXCEL)) {
    printer.printRecord("SEP=,"); //this line does the margic.
    printer.printRecord("Column A","Column B","Column C");                      
} catch (IOException ex) {
    
}


来源:https://stackoverflow.com/questions/54746499/csvprinter-datas-appears-not-separated-in-columns

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!