简体   繁体   English

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

[英]How to wrap the cell when writing CSV file using CSVWriter in OpenCSV in java?

I'm trying to convert the XML file to CSV. 我正在尝试将XML文件转换为CSV。 Parsing the XML and converting is done. 解析XML并完成转换。 While writing to the CSV file I'm having issue. 写入CSV文件时出现问题。 If the data is having the 'new line' (ie, \\n or \\r), it is coming in the next record as new. 如果数据具有“换行”(即\\ n或\\ r),则它将作为新数据进入下一条记录。 Due to this I'm not able to produce the correct document using OpenCSV CSVWriter. 因此,我无法使用OpenCSV CSVWriter生成正确的文档。 I need to wrap the cell so that it can access/write the data into that cell. 我需要包装单元格,以便它可以访问/写入数据到该单元格中。

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

Above the CSVWriter I'm creating and writing the data as below: 在CSVWriter上方,我正在创建和写入数据,如下所示:

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

Input XML file: 输入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>

Expected output: 预期产量:

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

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

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

Help would be appreciated. 帮助将不胜感激。

I don't know why OpenCsv is not writing the format you need, but univocity-parsers can do it. 我不知道为什么OpenCsv没有编写您需要的格式,但是univocity解析器可以做到。 You could do this: 您可以这样做:

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

Then update your method: 然后更新您的方法:

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

When you are done, call 完成后,致电

writer.close();

Hope this helps 希望这可以帮助

Disclosure: I'm the author of this library. 披露:我是这个图书馆的作者。 It's open-source and free (Apache 2.0 license) 它是开源且免费的(Apache 2.0许可证)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM