0

I want to write a string into one Column in an .csv (Excel) file. My Problem is that the string is written into multiple Columns.the string is written into multiple Columns

In this screenshot for example I have 20 Columns.

        GetMetadataCompleteResponse resultValue = null;
        string jsonData = null;

        await Task.Run(() =>
        {
            byte[] rawData = Convert.FromBase64String(responseContent);
            jsonData = CompressUtil.Unzip(rawData);
        });

        resultValue = JsonConvert.DeserializeObject<GetMetadataCompleteResponse>(jsonData);

       foreach(string a in resultValue.Value.Values)
            {
                foreal += a;
            }
       await Log.Info("callWebservice for " + strUrl + ", Result: " + objErrorDetails.Code + ", " + foreal);

edit

I've noticed that the new Column starts after every ';'(semicolon). I probably can just replace it with something else.

4
  • Is your json flat? If not.. CSV is the wrong format. Commented May 14, 2019 at 13:42
  • @TheIncorrigible1 hey there. I'm quite new to json. What is mean with flat json? Commented May 14, 2019 at 13:46
  • 1
    I mean, does your JSON have nested objects? Commented May 14, 2019 at 13:47
  • @nalnpir oh yeah it is. Commented May 14, 2019 at 13:48

1 Answer 1

1

I think you have 2 issues. The first one is how you write your CSV with simple string concatenation. With no escaping or double quote. The Json will have commas , that will be separator in your CSV.

In order to produc e a valid CSV you should read the RFC 4180 and use a proper library to handle the Serialisation.

Here is an Minimal, Complete, and Verifiable example of writing a Json in a CSV column.

using CsvHelper;
using CsvHelper.Configuration;
using Newtonsoft.Json;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
                    
public class Program
{
    public static void Main()
    {
        var input = new Foo
        {
            Label = "My Foo",
            Bars = new List<Bar> {
                new Bar{Label="Bar2"},
                new Bar{Label="Bar1"},
                new Bar{Label="Bar3"},
            }
        };

        var json = JsonConvert.SerializeObject(input);

        var myObject = new CsvObject
        {
            Label = "My CSV object",
            FooString = json,
        };

        var result = "";

        // Writing into a string instead of a file for debug purpuse. 
        using (var stream = new MemoryStream())
        using (var reader = new StreamReader(stream))
        using (var writer = new StreamWriter(stream))
        using (var csv = new CsvWriter(writer))
        {

            csv.Configuration.RegisterClassMap<CsvObjectMap>();

            csv.WriteHeader<CsvObject>();                
            csv.NextRecord();

            csv.WriteRecord(myObject);                
            csv.NextRecord();

            writer.Flush();
            stream.Position = 0;
            result = reader.ReadToEnd();
        }
        Console.WriteLine(result);
    }
    
    private sealed class CsvObjectMap : ClassMap<CsvObject>
    {
        public CsvObjectMap()
        {
            Map( m => m.FooString );
            Map( m => m.Label );
        }
    }
    public class CsvObject
    {
        public string Label { get; set; }
        public string FooString { get; set; }
    }
    public class Foo
    {
        public string Label { get; set; }
        public List<Bar> Bars { get; set; }
    }
    public class Bar
    {
        public string Label { get; set; }
    }
}

Live demo : https://dotnetfiddle.net/SNqZX1

In this exemple I have used CsvHelper for CSV serialisation, and Json.NET for the Json serialisation. Note that Writing a CSV to a file is a more simlpe task that to a string like in this example

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.