Converting DataSet/DataTable to CSV

后端 未结 5 460
梦谈多话
梦谈多话 2020-12-11 07:09

Please let me know, if there any way to generate CSV files from a DataTable or DataSet? To be specific, without manually iterating through rows of DataTable and concatenatin

5条回答
  •  独厮守ぢ
    2020-12-11 07:55

    So this is a fairly bizarre solution, but it works faster than most as it makes use of the JSON.net library's serialization. This speeds the solution up significantly.

    Steps:

    1. Create array of every column name in the data table, should be simple
    2. Use JSON.net to convert datatable to a json string

      string json = JsonConvert.SerializeObject(dt, Formatting.None);

    3. Begin making use of the Replace function on c# strings and strip the json string of all json formatting.

      json = json.Replace("\"", "").Replace("},{", "\n").Replace(":", "").Replace("[{", "").Replace("}]", "");

    4. Then use the array from step 1 to remove all column names from the json string. You are left with a csv formatted string.

    5. Consider using the array created in step 1 to add the column names back in as the first row in csv format.

提交回复
热议问题