Converting a csv file to json using C#

后端 未结 14 1714
余生分开走
余生分开走 2020-12-04 22:10

I was wondering if someone\'s written a utility to convert a CSV file to Json using C#. From a previous question on stackoverflow, I\'m aware of this nice utility - https://

14条回答
  •  忘掉有多难
    2020-12-04 22:50

    First, load the csv file into datatable and serialize it to Json document. It uses OLEDB Provider that can parse the csv wisely,

    Courtesy to Jim Scott, https://stackoverflow.com/a/1050278/6928056

    Courtesy to K_B, https://stackoverflow.com/a/2979938/6928056

    using System.Data;
    using System.Data.OleDb;
    using System.Globalization;
    using System.IO;
    using Newtonsoft.Json;
    
    static string ConvertCsvToJson(string path, bool isFirstRowHeader)
    {
        string header = isFirstRowHeader ? "Yes" : "No";
    
        string pathOnly = Path.GetDirectoryName(path);
        string fileName = Path.GetFileName(path);
    
        string sql = @"SELECT * FROM [" + fileName + "]";
    
        using(OleDbConnection connection = new OleDbConnection(
                  @"Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + pathOnly + 
                  ";Extended Properties=\"Text;HDR=" + header + "\""))
        using(OleDbCommand command = new OleDbCommand(sql, connection))
        using(OleDbDataAdapter adapter = new OleDbDataAdapter(command))
        {
            var dataTable = new DataTable();
            dataTable.Locale = CultureInfo.CurrentCulture;
            adapter.Fill(dataTable);
            return JsonConvert.SerializeObject(dataTable, Formatting.Indented);
        }
    }
    

提交回复
热议问题