5
Answers

C# Importing CSV files into datatables

M

M

16y
75.1k
1

I have an application that contains a dataset with a few datatables.  I have a few .csv files that I'd like to load into the datatables. Can that be done?  If so, how?

Thanks!

Answers (5)
0
Sanjeeb Lenka

Sanjeeb Lenka

NA 22.1k 1.3m 11y
0
Iftikar Hussain

Iftikar Hussain

NA 18.9k 275.4k 11y
Hi,
        Try like this

public DataTable CsvFileToDatatable(string path, bool IsFirstRowHeader)
{
string header = "No";
string sql = string.Empty;
DataTable dataTable = null;
string pathOnly = string.Empty;
string fileName = string.Empty;
try
{
pathOnly = Path.GetDirectoryName(path);
fileName = Path.GetFileName(path);
sql = @"SELECT * FROM [" + fileName + "]";
if (IsFirstRowHeader)
{
header = "Yes";
}
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))
{
dataTable = new DataTable();
dataTable.Locale = CultureInfo.CurrentCulture;
adapter.Fill(dataTable);
}
}
}
}
finally
{
}
return dataTable;
}

Regards,
Iftikar
0
jason smith

jason smith

NA 5 2k 11y

C# CSV Parser


This library can parse just about anything in CSV files.  It is cheap too:

http://www.kellermansoftware.com/p-50-csv-reports.aspx
0
Doug Fresh

Doug Fresh

NA 2 0 14y
Amazing Alan this worked like a champ. Well done.
0
Alan

Alan

NA 8.3k 0 16y

You can do this quite easily in simple cases where the fields in each row in the CSV file are in the same order as the corresponding columns in the DataTable:

   public static void TransferCSVToTable(DataTable dt, string  filePath)
   {
       string[] csvRows = System.IO.File.ReadAllLines(filePath);
       string[] fields = null;
       foreach(string csvRow in csvRows)
       {
          fields = csvRow.Split(',');
          DataRow row = dt.NewRow();
          row.ItemArray = fields;
          dt.Rows.Add(row);
       }
   }

In other cases, you'll need to manipulate the 'fields' array first or assign fields to columns individually.

Next Recommended Forum