猿问

带有换行符的 CSVPrinter

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


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


我应该手动替换/删除这些字符还是有办法配置 CSVPrinter 以自动删除它?


谢谢大家。F


编辑:这里是一个代码片段:



    CSVFormat csvFormat = CSVFormat.DEFAULT.withRecordSeparator("\n").withQuoteMode(QuoteMode.ALL).withQuote('"');

    CSVPrinter csvPrinter = new CSVPrinter(csvContent, csvFormat);


    // 准备从数据库收集的字符串列表。我明确使用 String 数组,因为我需要在将其写入 CSV 之前对 DB 内容执行一些文本编辑

    List fasciaOrariaRecord = new ArrayList();

    时间bandRecord.add(...);

    时间bandRecord.add(...);

    // ...


    csvPrinter.printRecord (csvHeader);


    // 更多行...


    csvPrinter.close();


手掌心
浏览 326回答 1
1回答

HUH函数

任何带有行结尾的值都应该用引号转义。如果您的 CSV 库没有自动为您执行此操作,我建议您使用univocity-parsers。在您的特定情况下,您可以使用一个预先构建的例程将数据库内容转储到 CSV 中。尝试这个:ResultSet resultSet = statement.executeQuery("SELECT * FROM table");//Get a CSV writer settings object pre-configured for ExcelCsvWriterSettings writerSettings = Csv.writeExcel(); writerSettings.setHeaderWritingEnabled(true); //writes the column names to the output fileCsvRoutines routines = new CsvRoutines(writerSettings);//use an encoding Excel likesroutines.write(resultSet, new File("/path/to/output.csv"), "windows-1252");希望这可以帮助。免责声明:我是这个库的作者。它是开源且免费的(Apache 2.0 许可)
随时随地看视频慕课网APP

相关分类

Java
我要回答