0 0 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 0 Amazing Alan this worked like a champ. Well done.
0 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.