带断行字符的 CSVPrinter

CSVPrinter with break line characters

我正在使用 org.apache.commons.csv.CSVPrinter (Java 8) 以生成从 DB RecordSet 开始的 CSV 文本文件。我的数据库 table 中有一个描述字段,用户可以在其中插入他想要的任何内容,例如换行!

当我在 Excel 或 Google 电子表格上导入 CSV 时,说明中的每一行都带有换行符,显然会破坏 CSV 结构。

我应该手动 replace/remove 这些字符,还是有办法配置 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();

任何带有行尾的值都应该用引号转义。如果您的 CSV 库没有自动为您执行此操作,我建议您使用 univocity-parsers. In your particular case, there is a 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 许可证)