masyita shariff
masyita shariff

Reputation: 110

Exporting mutiline data into same cell in csv

I understand that this question have been asked many times (1, 2 & 3) but I just don't understand how to apply it in my case. I have tried playing around for hours but I cannot get it right.

I have variables in the form of List<string>where each list contain datas that have line breaks between them/multiline data. Then I called an event that would export these datas in a CSV file. Below is my code.

savestate.cs - class where I initialized the variables

public partial class Savestate
 { 
    public static List<string> rtb1_list = new List<string>();
    public static List<string> rtb2_list = new List<string>();
    public static List<string> rtb3_list = new List<string>();
    public static List<string> rtb4_list = new List<string>();
 }

Form1.cs - The event

public void Savetocsv()
    {
      Type s = typeof(Savestate);
      FieldInfo[] fields = s.GetFields(BindingFlags.Public | BindingFlags.Static);

      StringBuilder csvdata = new StringBuilder();
      string header = String.Join(",", fields.Select(f => f.Name).ToArray());
      csvdata.AppendLine(header);

      string rtb1 = String.Join(",", Savestate.rtb1_list.ToArray());
      string rtb2 = String.Join(",", Savestate.rtb2_list.ToArray());
      string rtb3 = String.Join(",", Savestate.rtb3_list.ToArray());
      string rtb4 = String.Join(",", Savestate.rtb4_list.ToArray());

      string newlinestring = string.Format("{0}; {1}; {2}; {3}", rtb1, rtb2, rtb3, rtb4);
      csvdata.AppendLine(newlinestring);

      string filepath = @"C:\new.csv";
      File.WriteAllText(filepath, csvdata.ToString());
    }

However when I opened the CSV file, the words are all over the place. For example I wrote hi then a new line then I wrote bye. This is the actual output and this is my intended output.Hope that I can get help.

Upvotes: 2

Views: 312

Answers (2)

Ali Ezzat Odeh
Ali Ezzat Odeh

Reputation: 2163

I suggest using CsvHelper Nuget Package when dealing with CSV, then try doing the following, I added an extension method to print each rtb list as one string:

public partial class Savestate
{
    public static List<string> rtb1_list = new List<string>() { "hi", "bye" };
    public static List<string> rtb2_list = new List<string>() { "hi", "bye" };
    public static List<string> rtb3_list = new List<string>() { "hi", "bye" };
    public static List<string> rtb4_list = new List<string>() { "hi", "bye" };
}

public static class SavestateExtensions
{
    public static string GetRtbListAsString(this IEnumerable<string> rtb_list)
    {
        StringBuilder str = new StringBuilder();

        foreach (var value in rtb_list)
        {
            str.AppendLine(value);
        }

        return str.ToString();
    }
}

Then use the CsvWriter from CSVHelper:

        using (var writer = new StreamWriter("file.csv"))
        {
            using (var csvWriter = new CsvWriter(writer))
            {
                csvWriter.Configuration.Delimiter = ";";
                csvWriter.Configuration.Encoding = Encoding.UTF8;

                csvWriter.WriteField("rtb1_list ");
                csvWriter.WriteField("rtb2_list ");
                csvWriter.WriteField("rtb3_list ");
                csvWriter.WriteField("rtb4_list ");
                csvWriter.NextRecord();

                csvWriter.WriteField(Savestate.rtb1_list.GetRtbListAsString());
                csvWriter.WriteField(Savestate.rtb2_list.GetRtbListAsString());
                csvWriter.WriteField(Savestate.rtb3_list.GetRtbListAsString());
                csvWriter.WriteField(Savestate.rtb4_list.GetRtbListAsString());
                csvWriter.NextRecord();
            }
        }

The output should be as the following:

enter image description here

Upvotes: 1

Mehrdad Dowlatabadi
Mehrdad Dowlatabadi

Reputation: 1335

To insert line breaks in csv file you need to surround string with double quotes, so desired output is generated by following code :

public partial class Savestate
{
    public static List<string> rtb1_list = new List<string>() { "hi1", "bye1" };
    public static List<string> rtb2_list = new List<string>() { "hi2", "bye2" };
    public static List<string> rtb3_list = new List<string>() { "hi3", "bye3" };
    public static List<string> rtb4_list = new List<string>() { "hi4", "bye4" };
}
public static void Savetocsv()
{
    Type s = typeof(Savestate);
    FieldInfo[] fields = s.GetFields(BindingFlags.Public | BindingFlags.Static);

    StringBuilder csvdata = new StringBuilder();
    string header = String.Join(",", fields.Select(f => f.Name).ToArray());
    csvdata.AppendLine(header);

    string rtb1 =  String.Join("\n", Savestate.rtb1_list.ToArray());
    string rtb2 =  String.Join("\n", Savestate.rtb2_list.ToArray());
    string rtb3 =  String.Join("\n", Savestate.rtb3_list.ToArray());
    string rtb4 =  String.Join("\n", Savestate.rtb4_list.ToArray());

    string newlinestring = string.Format("\"{0}\",\" {1}\",\" {2}\",\" {3}\"", @rtb1, @rtb2, @rtb3, @rtb4);
    csvdata.AppendLine(newlinestring);

    string filepath = @"new.csv";
    File.WriteAllText(filepath, csvdata.ToString());
}

Output file:

enter image description here

Upvotes: 2

Related Questions