Comments (23)
I worked it out. :)
StreamReader reader = new StreamReader("file.csv");
Data d = new Data();
CsvConfiguration csvConfig = new CsvConfiguration();
foreach (var key in postdata.AllKeys)
{
string val = postdata[key].ToString();
if (val != "")
{
PropertyInfo dMember = d.GetType().GetProperty(key);
CsvPropertyMap newMap = new CsvPropertyMap(dMember);
newMap.Name(val);
csvConfig.Properties.Add(newMap);
}
}
var csv = new CsvReader(reader, csvConfig);
var theData = csv.GetRecords<Data>();
return View("CsvOutput", theData);
from csvhelper.
Nice. Before I even saw the email. :)
from csvhelper.
The above posts helped me immensely! Here is how I did it:
....
....
csvReader.Configuration.Properties.Add(csvReader.Configuration.PropertyMap<Call>(call => call.ANI).Index(client.CsvAniColumnIndex));
csvReader.Configuration.Properties.Add(csvReader.Configuration.PropertyMap<Call>(call => call.DateScheduled).Index(client.CsvDateColumnIndex));
csvReader.Configuration.Properties.Add(csvReader.Configuration.PropertyMap<Call>(call => call.Id).Ignore());
csvReader.Configuration.Properties.Add(csvReader.Configuration.PropertyMap<Call>(call => call.IsQueued).Ignore());
....
....
That worked for me. I wonder if that is also a good and correct way of doing things. Great library btw! Very well thought out and efficient. Thx!
from csvhelper.
The correct way is to create a class that derives from CsvClassMap<T>
and register that mapping with the config.
https://github.com/JoshClose/CsvHelper/wiki/Fluent-Class-Mapping
from csvhelper.
Josh,
I looked at the fluent mapping but I see you are creating sealed classes. Now this would work if I knew the indices before hand.
If you notice my code snippet you'll see that I will not know the indices until a DB hit is performed. So can I still create a sealed class dynamically during run time and still continue registering it in the config?
Pardon my noobness but I'm still learning the ropes. It would be great if you can also provide a snippet illustrating the same.
Thanks!
from csvhelper.
It doesn't have to be sealed. The reason it is sealed is because the methods are being called in the constructor. You could definitely do it a different way.
The way you're doing it is perfectly fine. Things will change a little in 2.0 though. The configuration holds a CsvClassMap
per type that you want to create records for. You can add class maps through csv.Configuration.Maps.Add( CsvClassMap map )
. There is a beta release of 2.0 on NuGet if you're interested.
I don't see a way in 2.0 to create a class map without it inheriting from another class. In your situation, you need to dynamically add all the maps, in which case you would have to create a dummy CsvClassMap
child class to add it before you would be able to add it to the maps... I made the CsvClassMap
class abstract for a reason, but I will have to see if there is any issue with making it not so you could create one and add properties to it without having to inherit.
from csvhelper.
Awesome. I'll just stick with what I have right now as this is working and the code will get pushed into production soon.
Thanks for pointing out about creating a dummy child class first and adding maps dynamically to it. I shall keep that in mind. I will wait for the GA release of 2.0 before starting to use that in my projects.
Once again thanks for all the help!
from csvhelper.
No problem.
from csvhelper.
In 2.0 I made CsvClassMap<>
not abstract so you will be able to create and instance of it and configure it, on the fly.
from csvhelper.
That is awesome. Thx! Looking forward to trying it out in the final release.
from csvhelper.
we use dynamic indexes as above and just upgraded from 1.4 to 2.2 to get a bug fix but CsvConfiguration.Properties has disappeared .. checked changelog but don't see anything obvious, figuring out how to rewrite on the fly using CsvClassMap
from csvhelper.
I had the same problem when I upgraded. see new code below:
StreamReader reader = new StreamReader("file.csv");
Data d = new Data();
// NEW * Define new MyMap:
MyMap myMap = new MyMap();
CsvConfiguration csvConfig = new CsvConfiguration();
foreach (var key in postdata.AllKeys)
{
string val = postdata[key].ToString();
if (val != "")
{
PropertyInfo dMember = d.GetType().GetProperty(key);
CsvPropertyMap newMap = new CsvPropertyMap(dMember);
newMap.Name(val);
// OLD* csvConfig.Properties.Add(newMap);
// NEW *
myMap.PropertyMaps.Add(newMap);
}
}
// NEW *
csvConfig.RegisterClassMap(myMap);
var csv = new CsvReader(reader, csvConfig);
var theData = csv.GetRecords<Data>();
return View("CsvOutput", theData);
from csvhelper.
forgot to add MyMap def as below:
private class MyMap : CsvClassMap<BatchData>
{
}
from csvhelper.
@itaylorweb - thanks. As inheriting from CsvClassMap<> is still required, I made my subclass generic with an empty CreateMap() - don't know if the automap feature is jumping in to save me but it seems to work ..
from csvhelper.
No Problem. Yep I have an empty CreateMap() too.
from csvhelper.
I'm REALLY hoping to remove the need for the abstract CreateMap
requirement. It is definitely annoying.
from csvhelper.
Hi I recently start working on csvhelper nuget package, above of your comments / answer I didn't get full idea about, How can I map class properties at runtime for writing csv file using csv helper?
& how can i runtime change for particular column data type? It would be great for me
if anyone send me sample code. Thanks !!!...
from csvhelper.
There is an example in the documentation. http://joshclose.github.io/CsvHelper/#mapping-runtime-mapping
from csvhelper.
Hi,
During runtime I want to change column name of csv file using csvhelper for this I write a below code but column name is not changed.
Ex: public class customer
{
public int cusId {get; set;}
public string cusName {get;set;}
}
DefaultCsvClassMap customerMap = new DefaultCsvClassMap();
CsvClassMap CustomerMap;
using(CsvWriter writer = new CsvWriter(new StreamWriter(filePath)))
{
foreach( string key in mapping.Keys )
{
var propertyInfo = typeof(T).GetType().GetProperty( key );
var newMap = new CsvPropertyMap( propertyInfo );
newMap.Name( columnName ); // Consider here I add new column name which I want to show in csv file ex: "CustomerId" & "CustomerName"
customerMap.PropertyMaps.Add( newMap ); // Here I already get proper Name properties & their type, no issues here
}
CustomerMap = custCodeMap;
writer.Configuration.RegisterClassMap(CustomerMap);
writer.WriteRecords(lstCustomer);
}
Assume list "lstCustomer" that contain customer type records having property name "cusId & "cusName"
By using these I want to export a record in csv file having column name "Customer Id" & "Customer Name" . But now in my case it export / write a csv file having column name "CusId" & "CusName"
Thanks !!!.....
from csvhelper.
The correct way is to create a class that derives from
CsvClassMap<T>
and register that mapping with the config.https://github.com/JoshClose/CsvHelper/wiki/Fluent-Class-Mapping
The link does not work anymore... Where can be found the actualized example?
from csvhelper.
https://joshclose.github.io/CsvHelper/examples/configuration/class-maps
from csvhelper.
Thanks for the link. Where can be found the mentioned example about the runtime mapping?
There is an example in the documentation. http://joshclose.github.io/CsvHelper/#mapping-runtime-mapping
from csvhelper.
Search the issues here. This has been asked several times. There are answers for this on stackoverflow.com too.
from csvhelper.
Related Issues (20)
- Microsoft.Bcl.AsyncInterfaces dependency error on System.Threading.Tasks.Extensions HOT 4
- ConfigurationException: 'Types that inherit IEnumerable cannot be auto mapped' when using custom class based on DynamicObject (NOT ExpandoObject) which also implements IDictionary HOT 3
- Missing "Product Version" in CsvHelper.dll HOT 1
- Column Name not displaying Using Mapping HOT 1
- Just thrown new exception by choice.
- Unexpected `InvalidCastException` in `TypeConverter<>` with nullable structs and value types HOT 2
- List<T>.ToAsyncEnumerable not accessible anymore after upgrade to CSVHelper 31.0.2 (.NET 8) HOT 5
- Set Custom Headers that derives from the property value. HOT 7
- Eliminate the columns if empty HOT 1
- Unregister ClassMap does not clear the previous maps if the same class is used HOT 2
- Getting problems with release build of my app using COM HOT 1
- add my report list columns' name as a header to the csv file when the HasHeaderRecord is set to false
- When Query from db and return IEnumable, will execute 2 times for sql query HOT 3
- Validate Header generate a very large message. HOT 2
- Header does not contain Quote, but some fields in row contain Quote, how should I read this kind of CSV HOT 4
- FastDynamicObject broke serialization HOT 7
- Using a ClassMap with custom type converter results in a "newed" object. HOT 1
- Using Custom TypeConverter causes dangerous/spurious CsvWriter behavior
- csv helper is writing 1 to 12 datetime in different format and 13 to 24 in different datetime format using version 4.0.30319 HOT 1
- FastDynamicObject ignores headers while used together with CsvWriter HOT 1
Recommend Projects
-
React
A declarative, efficient, and flexible JavaScript library for building user interfaces.
-
Vue.js
🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
-
Typescript
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
-
TensorFlow
An Open Source Machine Learning Framework for Everyone
-
Django
The Web framework for perfectionists with deadlines.
-
Laravel
A PHP framework for web artisans
-
D3
Bring data to life with SVG, Canvas and HTML. 📊📈🎉
-
Recommend Topics
-
javascript
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
-
web
Some thing interesting about web. New door for the world.
-
server
A server is a program made to process requests and deliver data to clients.
-
Machine learning
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
-
Visualization
Some thing interesting about visualization, use data art
-
Game
Some thing interesting about game, make everyone happy.
Recommend Org
-
Facebook
We are working to build community through open source technology. NB: members must have two-factor auth.
-
Microsoft
Open source projects and samples from Microsoft.
-
Google
Google ❤️ Open Source for everyone.
-
Alibaba
Alibaba Open Source for everyone
-
D3
Data-Driven Documents codes.
-
Tencent
China tencent open source team.
from csvhelper.