how to use comma in csv columns [duplicate]
Asked Answered
D

2

30

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??

Dirham answered 21/4, 2011 at 6:27 Comment(0)
D
8

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

Deena answered 21/4, 2011 at 6:32 Comment(0)
V
73
       // 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("\"", "\"\"");
            data = String.Format("\"{0}\"", data);
        }
        else if (data.Contains(",") || data.Contains(System.Environment.NewLine))
        {
            data = String.Format("\"{0}\"", data);
        }

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

Vermouth answered 21/4, 2011 at 6:43 Comment(5)
I think this item should be: if (data.Contains("\"")) { data = String.Format("\"{0}\"", data.Replace("\"", "\"\"")); } as an escaped quote must be in a string that is itself within quotes.Dayfly
With excel 2013, need open file with notepad++, add sep=, at the first line.Inconsonant
You may want to consider combining the check for a comma and the check for a newline so that you don't end up with two sets of quotes surrounding the string when both conditions exist.Triangular
this is really great answer, but it is much better to use .IndexOf() method instead of Contains - you will gain 10x performance with that.Spadework
well, if a string has commas and new lines at the same time this code will not encode the string properlySpadework
D
8

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

Deena answered 21/4, 2011 at 6:32 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.