How to convert any string to a valid CSV field?

I need to save a table to a CSV file. Each cell of the table may contain rows with such characters as: ",;" and new lines.
How to convert these lines to valid CSV fields that could be opened in Excel?

+4
source share
6 answers

It should be so simple:

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

This wraps the cell’s text in double quotation marks and skips the double quotation marks inside the double quotation mark cell.

+10
source

Wrap each cell / value with double quotation marks or use the tab as a delimiter \ t.

You need to look at our doube quotes in a cell / value, you can replace them with single quotes or use escape char.

Eaxmple:

 "Test", "test,123", "test 123", "test 123", "test 345" "Test", "test,123", "test 123", "test 123", "test 345" "Test", "test,123", "test 123", "test 123", "test 345" 
+2
source

I know this is old, but here is my solution as an extension method for an object class:

 public static class ObjectUtil { public static string ToCsvString(this object obj) { string result = obj.ToString(); if (result.Contains("\"")) { result = result.Replace("\"", "\"\""); } if (result.Contains(",")) { result = string.Format("\"{0}\"", result); } if (result.Contains(Environment.NewLine)) { result = string.Format("\"{0}\"", result); } return result; } } 
+2
source

I would look at the formal CSV specification for further guidance.

+1
source

I would replace the carriage return with spaces and then wrap each text value with double quotes.

I did not try to use files with shared partitions, but could I use this to remove any ambiguity with characters?

0
source

Here's a line extension to handle this simply

 public static string Escape(this string value) { return string.Format("\"{0}\"", (value ?? string.Empty).Replace("\"", "\"\"")); } 
0
source

Source: https://habr.com/ru/post/1345865/


All Articles