【问题标题】:CSVPrinter remove quotes only from headerCSVPrinter 仅从标题中删除引号
【发布时间】:2021-08-26 08:26:43
【问题描述】:

当引用值时,我需要在模式下使用来自 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"

【问题讨论】:

  • 使用 commons-csv 是不可能的。您不能动态更改 QuoteMode。

标签: java csv apache-commons


【解决方案1】:

您可以对标题使用一种格式,对记录使用另一种格式。

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

【讨论】:

    【解决方案2】:

    其实由于流是使用 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();
    
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-02-18
      • 1970-01-01
      • 1970-01-01
      • 2016-02-15
      • 1970-01-01
      • 2016-09-26
      • 2022-10-22
      • 2020-05-26
      相关资源
      最近更新 更多