为了账号安全,请及时绑定邮箱和手机立即绑定

带有换行符的 CSVPrinter

带有换行符的 CSVPrinter

手掌心 2021-10-17 10:59:13
我正在使用 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();
查看完整描述

1 回答

?
HUH函数

TA贡献1836条经验 获得超4个赞

任何带有行结尾的值都应该用引号转义。如果您的 CSV 库没有自动为您执行此操作,我建议您使用univocity-parsers。在您的特定情况下,您可以使用一个预先构建的例程将数据库内容转储到 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 许可)


查看完整回答
反对 回复 2021-10-17
  • 1 回答
  • 0 关注
  • 325 浏览

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信