[英]CSVPrinter remove quotes only from header
當引用值時,我需要在模式下使用來自 Apache 的 commons 的 CSVPrinter,但 header 不是。 看起來報價模式只有一個選項,影響 header 和值。 這可以獨立完成嗎?
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();
給出:
"a", "b"
"a val", "b val"
"1", "2"
但要求是:
a,b
"a val", "b val"
"1", "2"
您可以對 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();
事實上,由於 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.