问题
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