简体   繁体   English

将Java中的字符串导出为CSV

[英]Export a string in Java to CSV

How to export a string in Java to a csv file having this format using only one column. 如何仅使用一列将Java中的字符串导出到具有这种格式的csv文件。

This is what i am expecting: 这是我所期望的:

                Column 1    
Row 1:     string1,string2,string3  
Row 2:     string4, string5, string6

Thanks in advance 提前致谢

In the code below you provide a List of elements. 在下面的代码中,您提供了元素列表。 Each element contains the info for one line of the csv file. 每个元素都包含csv文件一行的信息。 The StringBuilder is used to create the String for one line, which then is output at once to the file. StringBuilder用于为一行创建字符串,然后将其立即输出到文件。

public void writeCsvFile(List elements, String fileName) throws IOException {    
     BufferedWriter csvFile = null;
     String delim = ",";
     try {
             csvFile = new BufferedWriter(new OutputStreamWriter(
                        new FileOutputStream(fileName), StandardCharsets.UTF_8));
             for (int i = 0; i < objects.size(); i++) {
                 StringBuilder buf = new StringBuilder();
                 Elements elem = elements.get(i);
                 buf.append(elem.info1).append(delim);
                 buf.append(elem.info2).append(delim);
                 buf.append(elem.info3);
                 csvFile.write(buf.toString());
                 csvFile.newLine();
            }
        } finally {
            try {
                if (csvFile != null) {
                    csvFile.close();
                }
            } catch (IOException e) {
                // empty
            }
        }

    }

You essentially have to "escape" the commas so the CSV reader won't interrpret them as columns delimiters. 本质上,您必须“转义”逗号,以便CSV阅读器不会将它们作为列定界符来解释。

If you wrap your row values in quotes then the commas should be ignored as delimeters 如果将行值用引号引起来,则逗号应忽略为分号

This will give you 3 columns 这将给您3列

Value1,Value2,Value3

This should give you 1 column with the entire string as a single value 这应该给您1列,整个字符串为单个值

"Value1,Value2,Value3"

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

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