Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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"
like image 992
msangel Avatar asked Apr 01 '26 15:04

msangel


1 Answers

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();
like image 107
Sascha Avatar answered Apr 04 '26 06:04

Sascha



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!