Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to convert any string to valid CSV field?

Tags:

c#

csv

I need to save table to CSV file. Each cell of table could contains strings with characters like: " , ; ' and new lines.
How to convert those strings to valid CSV fields that could be opened in Excel?

like image 637
Marek Kwiendacz Avatar asked Mar 30 '11 10:03

Marek Kwiendacz


People also ask

What is a valid CSV file?

A CSV file must contain every column for all attributes of its object type. If the attribute value is not required, a column must exist with the attribute name and a comma for any blank attribute values. If a column is defined as optional, it means that the column is required to exist, but the value can be blank.

How do I store numbers as text in a CSV file?

To preserve all the digits in text-formatted numbers, you have to import the downloaded CSV file as raw data into a new Excel spreadsheet, set the column datatypes as needed, and then save the new file as an Excel workbook. Excel (XLSX) files will preserve these formats, CSV files won't.


1 Answers

It should be as simple as this:

csvCell = "\"" + cell.Replace("\"", "\"\"") + "\"";

This wraps the cell text in "double quotes" and escapes "double quotes" inside the cell with double "double quotes".

like image 109
Daniel Hilgarth Avatar answered Oct 06 '22 02:10

Daniel Hilgarth