Import CSV data into objects in C# with mappings for column and property names | Generic method

preview_player
Показать описание
This video demonstrates how easy it to import data from a csv with different column and property names by writing a generic method. We can use a list of KeyValuePair objects for the mappings and use this while importing data into objects.

Credits:
Music: YouTube Audio Library
Technology: C#
Editor : LinqPad
Рекомендации по теме
Комментарии
Автор

Thanks for your wonderful video bro!
How to access data from few cells without any headings ? For eg from a particular Excel>Worksheet>Cell such as C3 ?

yours.trustworthy
Автор

Any idea why i get
prop.SetValue(obj, Convert.ChangeType(value, propType)); Object must implement Iconvertible

CarbonFanatic
Автор

My excel columns contains spaces and i need to convert it into xml file so this code will work?

roshankj
Автор

Used online OCR to extract code. :->

public class Product

{

public string ID { get; set; }
public string Name { get; set; }
public double Price { get; set; }
public int Units { get; set; }
}

public class Importer
{
public List<KeyValuePair<string, string>> Mappings;
public List<T> Import<T>(string file)
{
List<T> list = new List<T>();
List<string> lines =
string headerLine = lines[0];
var headerInfo = headerLine.Split(', ').ToList().Select((v, i) => new
{
ColName = v,
ColIndex = i
});
Type type = typeof(T);
var properties = type.GetProperties();
var dataLines = lines.Skip(1);
=>
{
var values = line.Split(', ');
T obj =
//Set values to object properties from csv columns
foreach (var prop in properties)
{
//find mapping for the prop
var mapping = Mappings.SingleOrDefault(m => m.Value == prop.Name);
var colName = mapping.Key;
var colIndex = headerInfo.SingleOrDefault(s => s.ColName == colName).ColIndex;
var value = values[colIndex];
var propType = prop.PropertyType;
prop.SetValue(obj, Convert.ChangeType(value, propType));
}
list.Add(obj);
});
return list;
}
}

shrinath
Автор

Conver.ChangeType doesn't work with nullable types

AndreiShchetkin
welcome to shbcf.ru