C# Store csv in DataTable
Sometimes I wanted to import data from a CSV file and put it in the DataTable.
Well, basically I think that is not so much…
I will leave it as a memorandum that can be used at such times.
Code to Convert csv to DataTable
Here is the code:
1 2 3 4 |
//Using requires the following using System.Data; using System.Data.OleDb;</span> |
The process to extract data from CSV is here.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
/// <summary> /// Get all data from csv file. /// </summary> /// <param name="filePath">Extraction source CSV</param> /// <returns></returns> public DataTable extractAllCsv(string filePath) { DataTable dt = new DataTable(); //Store the acquired data string csvDir = Path.GetDirectoryName(filePath); //Folder where CSV file is placed string csvFileName = Path.GetFileName(filePath); //CSV file name //Connection string string connectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + csvDir + ";Extended Properties=\"text;HDR=Yes;FMT=Delimited\""; OleDbConnection con = new OleDbConnection(connectionString); //Get from csv file string commText = "SELECT * FROM [" + csvFileName + "]"; OleDbDataAdapter da = new OleDbDataAdapter(commText, con); da.Fill(dt); return dt; }</span> |
https://overseas.loosecarrot.com/2019/03/25/85