在C#中从CSV文件创建JSON文件

qxsslcnc  于 2023-10-13  发布在  C#
关注(0)|答案(1)|浏览(119)

抱歉,但这将是一个“如何”的问题,而不是一个技术问题。我对C#和使用JSON非常陌生。我有一个CSV文件如下:
编辑-我在这里找到了一些代码-https://qawithexperts.com/article/c-sharp/convert-csv-to-json-in-c/465-不确定这是否适合我的目标,因为它似乎是一个简单的转换。

Time             Control_Code   Metric  Organisation    Value   DateTime

2018-10-21T00:08:03 JKX           3721      AD450          20   2018-10-21T00:08:00
2018-10-21T00:08:03 BHY           1234      HG650          88   2018-10-21T00:08:00

我需要在下面的格式示例中从该csv生成多个JSON输出文件:

{
    "Time":"2018-10-21T00:08:03",
    "Control_Code": "JKX",
    "metrics": [
        {
            "Metric": 3721,
            "Organisation":"AD450",
            "Value": 20,
            "Datetime":"2018-10-21T00:08:00"
        },
        {
            "Metric": 1234,
            "Organisation":"HG650",
            "value": 88,
            "datetime":"2018-10-21T00:08:00"
        }
        
    ]
}

现在,在此之上的额外问题部分是,每个JSON只能使用一个Control_Code的要求。生成的每个Json必须包含一个Control_Code和metrics数组中所有相关的metric值。因此,需要针对每个不同的Control_Code扫描csv,然后为该特定Control_Code生成输出,然后对任何后续Control_Code执行相同的操作。
因此,例如,不同的JSON将使用不同的Control_Code(来自同一个CSV文件)生成- Example(注意不同的Control_Code其他值当然也会改变,但只是提供一个示例)。

{
    "Time":"2018-10-21T00:08:03",
    "Control_Code": "BHY",
    "metrics": [
        {
            "Metric": 3721,
            "Organisation":"AD450",
            "Value": 20,
            "Datetime":"2018-10-21T00:08:00"
        },
        {
            "Metric": 1234,
            "Organisation":"HG650",
            "value": 88,
            "datetime":"2018-10-21T00:08:00"
        }
        
    ]
}

感谢您提前提供的任何建议/信息。

vlf7wbxs

vlf7wbxs1#

This is how excel files converts in to JSON. hope you can use it.At the end I added my GitHub solution URL. if any doughts, please refer it

    public class CityReader
    {
        private readonly ILogger<CityReader> logger;
        private readonly IConfiguration configuration;

        public CityReader(ILogger<CityReader> logger, IConfiguration configuration)
        {
            this.logger = logger;
            this.configuration = configuration;
        }

        public void Read()
        {
            string filePath = configuration.GetValue<string>("File:City");

            using (var stream = File.Open(filePath, FileMode.Open, FileAccess.Read))
            {
                // Auto-detect format, supports:
                //  - Binary Excel files (2.0-2003 format; *.xls)
                //  - OpenXml Excel files (2007 format; *.xlsx, *.xlsb)
                using (var reader = ExcelReaderFactory.CreateReader(stream))
                {
                    // 2. Use the AsDataSet extension method
                    var result = reader.AsDataSet(new ExcelDataSetConfiguration()
                    {
                        ConfigureDataTable = (tableReader) => new ExcelDataTableConfiguration()
                        {
                            FilterRow = (rowReader) =>
                            {
                                int progress = (int)Math.Ceiling(rowReader.Depth / (decimal)rowReader.RowCount * 100);
                                // progress is in the range 0..100
                                return true;
                            },
                            UseHeaderRow = true
                        }
                    });

                    // The result of each spreadsheet is in result.Tables
                    int count = 0;
                    List<CityViewModel> cities = new List<CityViewModel>();

                    foreach (DataTable table in result.Tables)
                    {
                        foreach (DataRow row in table.Rows)
                        {
                            var id = row.Field<double>(0);
                            var districtId = row.Field<double>(1);
                            var name = row.Field<string>(2);
                            var postcode = row.Field<double>(3);
                            var latitude = row.Field<double>(4);
                            var longitude = row.Field<double>(5);

                            logger.LogInformation("id: {0}, districtId: {1}, postcode: {2}, latitude: {3}, longitude: {4} ", id, districtId, postcode, latitude, longitude);

                            var city = new CityViewModel
                            {
                                //Id = Convert.ToInt32(id),
                                DistrictId = Convert.ToInt32(districtId),
                                IsActive = true,
                                Name = name,
                                PostCode = postcode.ToString(),
                                Latitude = (float)latitude,
                                Longitude = (float)longitude

                            };
                            cities.Add(city);
                        }
                    }

                    var json = JsonConvert.SerializeObject(cities, Formatting.Indented);

                    string path = Path.Combine(
                        Directory.GetCurrentDirectory(),
                        configuration.GetValue<string>("File:Results"),
                        "cities.json");

                    logger.LogInformation("Writing countries to {0}", path);

                    File.WriteAllText(path, json);
                }
            }
        }
    }

public Task StartAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("Starting IHostedService registered in Startup");
            cityReader.Read();

            return Task.CompletedTask;
        }

        public Task StopAsync(CancellationToken cancellationToken)
        {
            _logger.LogInformation("StoppingIHostedService registered in Startup");
            return Task.CompletedTask;
        }

https://github.com/Chamaxonline/car_classified_ads/tree/master/Application/Tools/ClassifiedAds.Tools.ExtractExcel

相关问题