Search code examples
c#export-to-csvstringbuilder

Export to CSV - How to write values which contain commas? c#


I currently have a string builder for exporting to a csv file. The values that are being exported in the CSV file contain commas in somw values.

Sometimes the data contains a "," causing it to generate incorrectly.

public string ExportActionMapAsCsv()
    {
        StringBuilder builder = new StringBuilder(",");
        List<EggEmbryoActivity> actions = GetActions();
        List<EggStatusActionMap> actionMaps = GetActionMaps();

        builder.AppendLine(string.Join(",", actions.Select(x => x.Title)));

        foreach (EggStatusActionMap actionMap in actionMaps)
        {
            builder.Append(actionMap.StatusDescription);
            builder.Append(",");
            builder.AppendLine(string.Join(",", actionMap.ActionMaskAsBinary.PadLeft(actions.Count, '0').ToCharArray()));
        }

        return builder.ToString();
    }

That is generating the export but how can I display data with commas in a single column


Solution

  • you will need to add quotation marks to the string you want to put a comma

         foreach (EggStatusActionMap actionMap in actionMaps)
         {
             builder.Append("\"" + neutralizeInput(actionMap.StatusDescription) + "\"");
             builder.Append(",");
             builder.AppendLine("\"" + neutralizeInput(string.Join(",", actionMap.ActionMaskAsBinary.PadLeft(actions.Count, '0').ToCharArray())) + "\"");
         }
    
         private string neutralizeInput(string input){
             return input.replace("\"", "\"\"")
         }