生成 CSV 文件,其中包含一些引用的值,而另一些则不引用
Generate CSV file with some values quoted and others not
我是编写 CSV 文件的新手,遇到一个找不到答案的场景。我需要生成一个没有 headers 的 CSV 文件,其中不引用数字值,引用字符串。一个例子是 - 71,72, "initial","2020-10-01".
我使用了以下的 CSVWriter 构造函数:
CSVWriter(FileWriter(ClassLoader.getSystemResource("mytable.csv").path), ',', '\'', '\"', "\n")
我试图用双引号填充我的字符串值,但这不起作用。
val linesForCSVUploadToTable = arrayOf(
someId.toString(),
someOtherId.toString(),
"\"initial\"",
"\"2020-10-15\"",
"\"2020-10-15\"",
"\"csv\"",//created_by
"\"2020-10-15\"",
"\"csv\"",
"\"csv\"",
"\"2020-10-15\""
)
输出为:
'100001','100001','""initial""','""2020-10-15""','""2020-10-15""','""csv""','""2020-10-15""','""csv""','""csv""','""2020-10-15""'
我必须对 id 进行 .toString,因为 writeAll() 和 writeNext() 函数似乎采用字符串数组,并且不接受 ANY 类型的数组。
我想避免编写自己的自定义 CSV 编写器。如果必须的话,那就这样吧。
我正在使用 OpenCSV 5.2 并用 Kotlin 编写。 Java 也有效。
如有任何帮助,我们将不胜感激!谢谢
您可能应该使用 Apache Commons CSV,它提供 NON_NUMERIC
引用策略并因此引用 CSV 文件中的任何 non-numeric 值。 示例:
try (Writer w = ...) {
CSVFormat outFormat = CSVFormat.newFormat(',')
.withRecordSeparator("\n")
.withQuote('\"')
.withQuoteMode(QuoteMode.MINIMAL);
CSVPrinter printer = new CSVPrinter(w, outFormat);
printer.printRecords(...);
}
我是编写 CSV 文件的新手,遇到一个找不到答案的场景。我需要生成一个没有 headers 的 CSV 文件,其中不引用数字值,引用字符串。一个例子是 - 71,72, "initial","2020-10-01".
我使用了以下的 CSVWriter 构造函数:
CSVWriter(FileWriter(ClassLoader.getSystemResource("mytable.csv").path), ',', '\'', '\"', "\n")
我试图用双引号填充我的字符串值,但这不起作用。
val linesForCSVUploadToTable = arrayOf(
someId.toString(),
someOtherId.toString(),
"\"initial\"",
"\"2020-10-15\"",
"\"2020-10-15\"",
"\"csv\"",//created_by
"\"2020-10-15\"",
"\"csv\"",
"\"csv\"",
"\"2020-10-15\""
)
输出为:
'100001','100001','""initial""','""2020-10-15""','""2020-10-15""','""csv""','""2020-10-15""','""csv""','""csv""','""2020-10-15""'
我必须对 id 进行 .toString,因为 writeAll() 和 writeNext() 函数似乎采用字符串数组,并且不接受 ANY 类型的数组。
我想避免编写自己的自定义 CSV 编写器。如果必须的话,那就这样吧。
我正在使用 OpenCSV 5.2 并用 Kotlin 编写。 Java 也有效。
如有任何帮助,我们将不胜感激!谢谢
您可能应该使用 Apache Commons CSV,它提供 NON_NUMERIC
引用策略并因此引用 CSV 文件中的任何 non-numeric 值。 示例:
try (Writer w = ...) {
CSVFormat outFormat = CSVFormat.newFormat(',')
.withRecordSeparator("\n")
.withQuote('\"')
.withQuoteMode(QuoteMode.MINIMAL);
CSVPrinter printer = new CSVPrinter(w, outFormat);
printer.printRecords(...);
}