OpenCSV引用空值

时间:2018-06-29 00:17:21

标签: java csv opencsv

使用OpenCSV库,调用StatefulBeanToCsv.write(),将我的空值括在引号中。

示例:

String[] columns = new String[] {
    "Col1",
    "Col2",
    "Col3"
};

ColumnPositionMappingStrategy strat = new ColumnPositionMappingStrategy();
strat.setColumnMapping(columns);

Writer writer = new FileWriter(outputFilePath);
StatefulBeanToCsv beanToCsv = new StatefulBeanToCsvBuilder(writer)
        .withMappingStrategy(strat)
        .build();
beanToCsv.write(items);
writer.close();

将产生:

1,"",3

当我期望的时候:

"1",,"3"

我没有通过.withApplyQuotesToAll(true)为所有字段设置引号。

如果我确实使用.withApplyQuotesToAll(true),我最终会得到

"1","","3"

在某一点上,库似乎与此相反:

OpenCSV CSVWriter does not add quote character for null element

我该如何使写为空白/空值而不是空字符串的值为空?

2 个答案:

答案 0 :(得分:0)

看起来您提到的未调用的方法实际上需要一个布尔值。您尝试过以下吗?

.withApplyQuotesToAll(false)

答案 1 :(得分:0)

有一种方法可以做到这一点。设置 .withApplyQuotesToAll(false) 告诉 OpenCSV 只引用具有特殊字符的元素,但我们可以改变 OpenCSV 理解的内容,像这样扩展 CSVWrite 类:

public class CustomCsvWriter extends CSVWriter {

    public CustomCsvWriter(Writer writer) {
        super(writer);
    }

    @Override
    protected boolean stringContainsSpecialCharacters(String line) {
        return !line.isEmpty();
     }
}

所以,你可以像这样创建一个 StatefulBeanToCsv:

new StatefulBeanToCsvBuilder<>(new CustomCsvWriter(writer))
   .withMappingStrategy(strat)
   .withApplyQuotesToAll(false)
   .build();

使用 OpenCSV 5.3 测试