【问题标题】:How to wrap the cell when writing CSV file using CSVWriter in OpenCSV in java?java - 在Java的OpenCSV中使用CSVWriter写入CSV文件时如何包装单元格?
【发布时间】:2018-08-06 14:31:32
【问题描述】:

我正在尝试将 XML 文件转换为 CSV。 解析 XML 并完成转换。在写入 CSV 文件时我遇到了问题。如果数据具有“新行”(即 \n 或 \r),它将作为新记录出现在下一条记录中。因此,我无法使用 OpenCSV CSVWriter 生成正确的文档。我需要包装单元格,以便它可以访问/将数据写入该单元格。

CSVWriter(new FileWriterWithEncoding(csvFile,StandardCharsets.UTF_8,true),",",'\u0000',CSVWriter.NO_ESCAPE_CHARACTER,"\n");

在 CSVWriter 之上,我正在创建和写入数据,如下所示:

public static boolean writeIntoCSVFile(CSVWriter writer, String[] cdrList) throws Exception {
        writer.writeNext(cdrList);
        writer.flush();
        return true;
    }

输入 XML 文件:

<?xml version="1.0" encoding="UTF-8"?>
<customers>
    <customer>
        <customers_email_address>abcd@gmail.com
        </customers_email_address>
    </customer>
    <customer>
        <customers_email_address>efgh@gmail.com
        </customers_email_address>
    </customer>
</customer>

预期输出:

+++++++++++++++
abcd@gmail.com

+++++++++++++++
efgh@gmail.com

+++++++++++++++

我们将不胜感激。

【问题讨论】:

    标签: java csv opencsv


    【解决方案1】:

    不知道为什么OpenCsv没有写出你需要的格式,但是univocity-parsers可以做到。你可以这样做:

    //configure the format as you want
    CsvWriterSettings settings = new CsvWriterSettings();
    settings.trimValues(false);
    settings.getFormat().setLineSeparator("\n");
    
    //create a CSV writer with the settings
    CsvWriter writer = new CsvWriter(new File("/path/to/your.csv"), "UTF-8", settings);
    

    然后更新你的方法:

    public static void writeIntoCSVFile(CsvWriter writer, String[] cdrList){
        writer.writeRow();
    }
    

    完成后,调用

    writer.close();
    

    希望对你有帮助

    披露:我是这个库的作者。它是开源和免费的(Apache 2.0 许可证)

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-12-07
      • 2018-06-04
      • 2022-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-07-18
      相关资源
      最近更新 更多