如何转换JsonResult到ClosedXml?

How to convert JsonResult to ClosedXml?

提问人:user1531040 提问时间:2/9/2022 更新时间:2/14/2022 访问量:300

问:

我有一个JSON格式的数据集。但是我怎样才能把它写成ClosedXML格式呢?

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

C# 模型视图控制器 数据表 closedXML JSONRESULT

评论


答:

0赞 user1531040 2/14/2022 #1

使用 PropertyInfo 和 Dictionary,您可以捕获 JSON 数据。

    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>();
    }