how to use comma in csv columns [duplicate]

怎甘沉沦 提交于 2019-12-05 12:40:54

问题


Possible Duplicate:
Dealing with commas in a CSV file

We are exporting a bulk data into a csv file for one of our projects. So in this case we have to export values like a,b,c,d which all have to be remain in one column. But the comma will separate them to different columns.

Like if we export some values entered in textarea or editor which contains character like \r\n will be exported as separate rows in csv. How can i solve this problem??


回答1:


The most common way to handle this is to use "" around the field, but depending on who is consuming your files it can be handled in a number of ways. You can delimit the commas, you can change the commas to a special value or use a different delimiter, but the most command




回答2:


       // CSV rules: http://en.wikipedia.org/wiki/Comma-separated_values#Basic_rules
        // From the rules:
        // 1. if the data has quote, escape the quote in the data
        // 2. if the data contains the delimiter (in our case ','), double-quote it
        // 3. if the data contains the new-line, double-quote it.

        if (data.Contains("\""))
        {
            data = data.Replace("\"", "\"\"");
        }

        if (data.Contains(","))
        {
            data = String.Format("\"{0}\"", data);
        }

        if (data.Contains(System.Environment.NewLine))
        {
            data = String.Format("\"{0}\"", data);
        }

data could be individual items from db or a property value of a type.



来源:https://stackoverflow.com/questions/5740359/how-to-use-comma-in-csv-columns

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!