2

So let's say I have a string entering into an Excel document set up like this

output.WriteLine(string.Format("{0},{1},{2},{3}",
                                                   var1,
                                                   var2,
                                                   var3,
                                                   var4
                                                   ));

Now normally it would enter each var into a separate cell. However, I find that if one of my vars has a comma in it, it will treat that as a cell ending, and go to the next one. How can I ignore commas in the vars while maintaining the set up?

proseidon
  • 2,235
  • 6
  • 33
  • 57

3 Answers3

7

I'm assuming this is a CSV file that you're creating. As such you would need to wrap the value that has the comma in it with double quotes. You can either wrap everything (which is easier, like:

output.WriteLine(string.Format("\"{0}\",\"{1}\",\"{2}\",\"{3}\"",
                                                   var1,
                                                   var2,
                                                   var3,
                                                   var4
                                                   ));

Or you could write a small helper function like:

public string EncodeCell(string value) {
   return value.Contains(",") ? String.Format("\"{0}\"", value) : value;
}

And then do:

output.WriteLine(string.Format("{0},{1},{2},{3}",
                                                   EncodeCell(var1),
                                                   EncodeCell(var2),
                                                   EncodeCell(var3),
                                                   EncodeCell(var4)
                                                   ));
CodingGorilla
  • 19,612
  • 4
  • 45
  • 65
1

Escape the commas in your vars before inserting with an escape sequence of your choice.

juergen d
  • 201,996
  • 37
  • 293
  • 362
  • If he wants it to open properly in Excel, then he has to use the supported escape, not one of his choice. This is the right approach overall though. – Ben Voigt Nov 14 '12 at 21:16
1

Depends on how you want comas entered. Simplest thing to do:

var1.Replace(",", "string to replace comma for")
var2.Replace(",", "string to replace comma for")
var3.Replace(",", "string to replace comma for")
...

Using list/array and String.Join would make it much easier too.

Euphoric
  • 12,645
  • 1
  • 30
  • 44