在Java中使用CSVWriter在CSV文件中写入CSV文件时,如何包装单元格?

时间:2018-08-06 14:31:33

标签: java csv opencsv

我正在尝试将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

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

我们将不胜感激。

1 个答案:

答案 0 :(得分:0)

我不知道为什么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许可证)