Reputation: 2305
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 var
s 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 var
s while maintaining the set up?
Upvotes: 2
Views: 934
Reputation: 12849
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.
Upvotes: 1
Reputation: 19842
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)
));
Upvotes: 7
Reputation: 204756
Escape the commas in your var
s before inserting with an escape sequence of your choice.
Upvotes: 1