Skip to content

Instantly share code, notes, and snippets.

@danielplawgo
Created December 17, 2018 04:24
Show Gist options
  • Save danielplawgo/7c38541c7e835178c129d5272489dcec to your computer and use it in GitHub Desktop.
Save danielplawgo/7c38541c7e835178c129d5272489dcec to your computer and use it in GitHub Desktop.
CsvHelper - praca z plikami csv
public class Category
{
public int Id { get; set; }
public string Name { get; set; }
}
private static string _fileName = "products.csv";
static void Export(IEnumerable<Product> products)
{
using (var writer = new StreamWriter(_fileName, false))
{
using (var csvWriter = new CsvWriter(writer))
{
csvWriter.WriteRecords(products);
}
}
}
private static string _fileName = "products.csv";
static void Export(IEnumerable<Product> products)
{
using (var writer = new StreamWriter(_fileName, false))
{
using (var csvWriter = new CsvWriter(writer))
{
csvWriter.Configuration.RegisterClassMap<ProductMap>();
csvWriter.WriteRecords(products);
}
}
}
static IEnumerable<Product> GetProducts()
{
int id = 1;
var categories = new Faker<Category>()
.RuleFor(p => p.Id, (f, p) => id++)
.RuleFor(p => p.Name, (f, p) => f.Commerce.Categories(1)[0])
.Generate(5);
id = 1;
return new Faker<Product>()
.RuleFor(p => p.Id, (f, p) => id++)
.RuleFor(p => p.Name, (f, p) => f.Commerce.ProductName())
.RuleFor(p => p.Category, (f, p) => f.PickRandom(categories))
.Generate(10);
}
static IEnumerable<Product> Import()
{
using (var reader = new StreamReader(_fileName))
{
using (var csvReader = new CsvReader(reader))
{
csvReader.Configuration.RegisterClassMap<ProductMap>();
return csvReader.GetRecords<Product>().ToList();
}
}
}
public class Product
{
public int Id { get; set; }
public string Name { get; set; }
public Category Category { get; set; }
public bool IsActive { get; set; } = true;
}
public class ProductMap : ClassMap<Product>
{
public ProductMap()
{
AutoMap();
Map(m => m.Category.Id).Name("CategoryId");
Map(m => m.Category.Name).Name("CategoryName");
Map(m => m.IsActive).Ignore();
}
}
Id;Name;Id;Name;IsActive
1;Awesome Fresh Pants;1;Health;True
2;Unbranded Frozen Bacon;2;Books;True
3;Incredible Rubber Pizza;1;Health;True
4;Fantastic Concrete Pants;2;Books;True
5;Practical Fresh Cheese;3;Beauty;True
6;Gorgeous Metal Chicken;2;Books;True
7;Fantastic Steel Hat;2;Books;True
8;Generic Steel Shirt;2;Books;True
9;Rustic Cotton Keyboard;5;Home;True
10;Unbranded Steel Pants;1;Health;True
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment