简体   繁体   中英

CSVPrinter remove quotes only from header

I need to use CSVPrinter from Apache's commons in mode when the values are quoted, but the header is not. It looks like there is the only option for quote mode, affecting header and values. Can this be done independently?

CSVFormat format = CSVFormat.DEFAULT.withHeader(new String(){"a", "b"})
                .withQuoteMode(QuoteMode.ALL);
CSVPrinter printer = new CSVPrinter(new FileWriter(new File("out.csv")), format);
printer.printRecord("a val", "b val");
printer.printRecord("1", "2");
printer.flush();
printer.close();

gives:

"a", "b"
"a val", "b val"
"1", "2"

But requirement is having this:

a,b
"a val", "b val"
"1", "2"

You can use one format for the header and another format for the records:

FileWriter writer = new FileWriter(new File("out.csv"));
CSVFormat formatHeader = CSVFormat.DEFAULT
                    .withHeader(new String[]{"a", "b"})
                    .withEscape('"').withQuoteMode(QuoteMode.NONE);
CSVFormat formatRecord = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL);
CSVPrinter headerPrinter = new CSVPrinter(writer, formatHeader);
headerPrinter.flush();
CSVPrinter recordPrinter = new CSVPrinter(writer, formatRecord);
recordPrinter.printRecord("a val", "b val");
recordPrinter.printRecord("1", "2");
recordPrinter.flush();
recordPrinter.close();
headerPrinter.close();

In fact, as the stream is truncated using FileWriter, the answer is to use another kind of out stream:

Path target = Files.createTempFile(null, ".csv");
BufferedWriter writer = Files.newBufferedWriter(
        target,
        StandardOpenOption.APPEND,
        StandardOpenOption.CREATE);
CSVFormat formatHeader = CSVFormat.DEFAULT.withHeader(new String[]{"a", "b"}).withEscape('"').withQuoteMode(QuoteMode.NONE);
CSVPrinter headerPrinter = new CSVPrinter(writer, formatHeader);
headerPrinter.flush(); 
headerPrinter.close(); 

CSVFormat format = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL);
writer = Files.newBufferedWriter(target, StandardOpenOption.APPEND, StandardOpenOption.CREATE); 
CSVPrinter printer = new CSVPrinter(writer, format)
printer.printRecord("a val", "b val");
printer.printRecord("1", "2");
printer.flush();
printer.close();

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM