Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to use comma in csv columns [duplicate]

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

like image 555
Mahesh KP Avatar asked Apr 21 '11 06:04

Mahesh KP


People also ask

How do you handle commas in a CSV file?

Since CSV files use the comma character "," to separate columns, values that contain commas must be handled as a special case. These fields are wrapped within double quotation marks. The first double quote signifies the beginning of the column data, and the last double quote marks the end.

Can CSV files have commas?

A comma-separated values (CSV) file is a delimited text file that uses a comma to separate values. Each line of the file is a data record. Each record consists of one or more fields, separated by commas.

How does SQL handle extra commas in CSV?

Values that contain commas must be enclosed within double quotes. Double quotes within quoted values must be escaped by doubling them. For example, here are two rows with three columns each.

How does everyone handle comma within a field in CSV file while importing it?

In case your Data Loader CSV file for import will contain commas for any of the field content, you will have to enclose the contents within double quotation marks " ".


1 Answers

       // 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.

like image 69
Vijay Sirigiri Avatar answered Sep 22 '22 15:09

Vijay Sirigiri