CSVPrinter 仅从标题中删除引号 [英] CSVPrinter remove quotes only from header

查看:25
本文介绍了CSVPrinter 仅从标题中删除引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当引用值时,我需要在模式下使用 Apache 的公共资源中的 CSVPrinter,但标题不是.看起来报价模式是唯一的选项,影响标题和值.这可以独立完成吗?

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

给出:

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

但是要求是这样的:

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

这篇关于CSVPrinter 仅从标题中删除引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆