CSV打印机仅从页眉中删除引号



当值被引用时,我需要在模式中使用Apache的commons中的CSVPrinter,但标头没有。报价模式似乎只有一个选项,会影响标题和值。这可以独立完成吗?

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"

您可以使用一种格式作为标题,另一种格式用于记录:

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();

事实上,由于使用FileWriter截断流,因此答案是使用另一种输出流:

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();

最新更新