简体   繁体   English

CSVPrinter 仅从 header 中删除引号

[英]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.当引用值时,我需要在模式下使用来自 Apache 的 commons 的 CSVPrinter,但 header 不是。 It looks like there is the only option for quote mode, affecting header and values.看起来报价模式只有一个选项,影响 header 和值。 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:您可以对 header 使用一种格式,对记录使用另一种格式:

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:事实上,由于 stream 是使用 FileWriter 截断的,答案是使用另一种输出 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();

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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