Search code examples
c#model-view-controllerdatatableclosedxmljsonresult

How to convert JsonResult to ClosedXml?


I have a dataset in a JSON-format. But how can I write this to a ClosedXML-format?

dataSet.Data { total = "123456", data = Count = 11, model '{\fields":{"DocumentId":{"title""...

    private void SetWorkbook(IXLWorkbook workbook, JsonResult dataSet)
    {
        var worksheet = workbook.Worksheets.Add("Export");

        DataTable dataTable = (DataTable)JsonConvert.DeserializeObject(dataSet.Data, (typeof(DataTable)));
        ....
    }

enter image description here


Solution

  • With PropertyInfo and Dictionary you can catch the JSON-data.

        private Dictionary<string, string> GetDataSet(object dataSet)
        {
            Type type = dataSet.GetType();
            System.Reflection.PropertyInfo[] properties = type.GetProperties();
    
            foreach (var property in properties)
            {
                if (property.Name == "data")
                {
                    Dictionary<string, string> dictionary = new Dictionary<string, string>();
                    dynamic data = property.GetValue(dataSet);
                    foreach (var rows in data)
                    {
                        foreach (var row in rows)
                        {
                            string value = string.Empty;
                            if (dictionary.ContainsKey(row.Key))
                                value = dictionary[row.Key] + "," + row.Value;
                            else
                                value = row.Value;
    
                            dictionary[row.Key] = value;
                        }
                    }
    
                    return dictionary;
                }
            }
    
            return new Dictionary<string, string>();
        }