Search code examples
javakotlinopencsv

Generate CSV file with some values quoted and others not


I am new to writing CSV files and have a scenario I can't find answers on. I need to generate a CSV file with no headers where number values are not quoted, strings are quoted. An example would be - 71,72, "initial","2020-10-01".

I used the CSVWriter Constructor of:

CSVWriter(FileWriter(ClassLoader.getSystemResource("mytable.csv").path), ',', '\'', '\"', "\n")

I tried to populate my string values with double quotes as so but this does not work.

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\""
            )

The output is:

'100001','100001','""initial""','""2020-10-15""','""2020-10-15""','""csv""','""2020-10-15""','""csv""','""csv""','""2020-10-15""'

I have to .toString the ids because the writeAll() and writeNext() functions appear to take a String Array and an array of type ANY isn't accepted.

I want to avoid writing my own custom CSV writer. If I have to then so be it.

I am using OpenCSV 5.2 and writing this in Kotlin. Java also works.

Any help would be much appreciated! Thanks


Solution

  • You probably should use Apache Commons CSV, which provides the NON_NUMERIC quoting strategy and thus quotes any non-numeric value in your CSV file. Example:

    try (Writer w = ...) {
        CSVFormat outFormat = CSVFormat.newFormat(',')
            .withRecordSeparator("\n")
            .withQuote('\"')
            .withQuoteMode(QuoteMode.MINIMAL);
        CSVPrinter printer = new CSVPrinter(w, outFormat);
        printer.printRecords(...);
    }