如何配置Apache Commons CSVPrinter仅数据值加引号、表头不加引号
该需求可以实现,核心思路是拆分表头和数据的输出逻辑,分别配置不同的引号策略,不需要依赖全局统一的QuoteMode配置,以下是可直接运行的实现代码:
import org.apache.commons.csv.CSVFormat; import org.apache.commons.csv.CSVPrinter; import org.apache.commons.csv.QuoteMode; import java.io.FileWriter; import java.io.IOException; public class CsvDemo { public static void main(String[] args) throws IOException { String[] headers = {"a", "b"}; FileWriter writer = new FileWriter("out.csv"); // 第一步:输出无引号的表头 CSVFormat headerFormat = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.NONE); try (CSVPrinter headerPrinter = new CSVPrinter(writer, headerFormat)) { headerPrinter.printRecord(headers); } // 第二步:输出全字段带引号的数据 CSVFormat dataFormat = CSVFormat.DEFAULT.withQuoteMode(QuoteMode.ALL); try (CSVPrinter dataPrinter = new CSVPrinter(writer, dataFormat)) { dataPrinter.printRecord("a val", "b val"); dataPrinter.printRecord("1", "2"); } } }
运行后输出的CSV内容完全符合预期:
a,b "a val","b val" "1","2"
注意事项
- 如果表头本身包含逗号、换行、双引号等CSV特殊字符,使用
QuoteMode.NONE会导致CSV格式错乱,这种场景建议改用QuoteMode.MINIMAL,仅当表头存在特殊字符时才自动加引号,平衡格式正确性和需求。 - 该实现兼容Apache Commons CSV 1.7及以上的主流版本。
内容的提问来源于stack exchange,提问作者msangel
相关产品推荐
相关产品推荐

