Coder Social home page Coder Social logo

Comments (23)

itaylorweb avatar itaylorweb commented on June 18, 2024

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.

JoshClose avatar JoshClose commented on June 18, 2024

Nice. Before I even saw the email. :)

from csvhelper.

karthicraghupathi avatar karthicraghupathi commented on June 18, 2024

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.

JoshClose avatar JoshClose commented on June 18, 2024

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.

karthicraghupathi avatar karthicraghupathi commented on June 18, 2024

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.

JoshClose avatar JoshClose commented on June 18, 2024

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.

karthicraghupathi avatar karthicraghupathi commented on June 18, 2024

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.

JoshClose avatar JoshClose commented on June 18, 2024

No problem.

from csvhelper.

JoshClose avatar JoshClose commented on June 18, 2024

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.

karthicraghupathi avatar karthicraghupathi commented on June 18, 2024

That is awesome. Thx! Looking forward to trying it out in the final release.

from csvhelper.

digiface avatar digiface commented on June 18, 2024

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.

itaylorweb avatar itaylorweb commented on June 18, 2024

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.

itaylorweb avatar itaylorweb commented on June 18, 2024

forgot to add MyMap def as below:

    private class MyMap : CsvClassMap<BatchData>
    {
    }

from csvhelper.

digiface avatar digiface commented on June 18, 2024

@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.

itaylorweb avatar itaylorweb commented on June 18, 2024

No Problem. Yep I have an empty CreateMap() too.

from csvhelper.

JoshClose avatar JoshClose commented on June 18, 2024

I'm REALLY hoping to remove the need for the abstract CreateMap requirement. It is definitely annoying.

from csvhelper.

vaibhavk10dec avatar vaibhavk10dec commented on June 18, 2024

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.

JoshClose avatar JoshClose commented on June 18, 2024

There is an example in the documentation. http://joshclose.github.io/CsvHelper/#mapping-runtime-mapping

from csvhelper.

vaibhavk10dec avatar vaibhavk10dec commented on June 18, 2024

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.

abrasat avatar abrasat commented on June 18, 2024

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.

JoshClose avatar JoshClose commented on June 18, 2024

https://joshclose.github.io/CsvHelper/examples/configuration/class-maps

from csvhelper.

abrasat avatar abrasat commented on June 18, 2024

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.

JoshClose avatar JoshClose commented on June 18, 2024

Search the issues here. This has been asked several times. There are answers for this on stackoverflow.com too.

from csvhelper.

Related Issues (20)

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    🖖 Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo 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.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google ❤️ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.