我正在使用org.apache.commons.csv.CSVPrinter(Java 8),以便从DB RecordSet开始生成CSV文本文件。我的数据库表中有一个描述字段,用户可以在其中插入他想要的任何内容,例如换行!
当我在Excel或Google Spreadsheet中导入CSV时,说明中每行带有换行符的行显然会破坏CSV结构。
我应该手动替换/删除这些字符,还是可以配置CSVPrinter以便自动删除?
提前谢谢大家。 F
编辑:这是一个代码段:
CSVFormat csvFormat = CSVFormat.DEFAULT.withRecordSeparator("\n").withQuoteMode(QuoteMode.ALL).withQuote('"'); CSVPrinter csvPrinter = new CSVPrinter(csvContent, csvFormat); // prepare a list of string gathered from the DB. I explicitly use a String array because I need to perform some text editing to DB content before writing it in the CSV List fasciaOrariaRecord = new ArrayList(); fasciaOrariaRecord.add(...); fasciaOrariaRecord.add(...); // ... csvPrinter.printRecord(csvHeader); // more rows... csvPrinter.close();
答案 0 :(得分:0)
任何带有行尾的值都应该用引号引起来。如果您的CSV库没有自动为您执行此操作,建议您使用univocity-parsers。在特定情况下,您可以使用pre-built routine将数据库内容转储为CSV。
尝试一下:
ResultSet resultSet = statement.executeQuery("SELECT * FROM table");
//Get a CSV writer settings object pre-configured for Excel
CsvWriterSettings writerSettings = Csv.writeExcel();
writerSettings.setHeaderWritingEnabled(true); //writes the column names to the output file
CsvRoutines routines = new CsvRoutines(writerSettings);
//use an encoding Excel likes
routines.write(resultSet, new File("/path/to/output.csv"), "windows-1252");
希望这会有所帮助。
免责声明:我是这个图书馆的作者。它是开源且免费的(Apache 2.0许可证)