Dynamically create a CSV file with FileHelpers

我们两清 提交于 2019-12-08 19:32:19

问题


FileHelpers supports a feature called "RunTime Records" which lets you read a CSV file into a DataTable when you don't know the layout until runtime.

Is it possible to use FileHelpers to create a CSV file at runtime in the same manner?

Based on some user input, the CSV file that must be created will have different fields that can only be known at runtime. I can create the needed Type for the FileHelper engine as described in their reading section, but I can't figure out what format my data needs to be in to be written.

var engine = new FileHelpers.FileHelperEngine(GenerateCsvType());

engine.WriteStream(context.Response.Output, dontKnow);

EDIT

Alternatively, can anyone suggest a good CSV library that can create a CSV file without knowing its fields until runtime? For example, create a CSV file from a DataTable.


回答1:


In fact the library only allows now to read runtime records but for writing purpouses you can use the DataTableToCsv method like this:

CsvEngine.DataTableToCsv(dt, filename);

Let me known if that helps.




回答2:


I know this is an old question, but I ran into same issue myself and spent some time looking for solution, so I decided to share my findings.

If you are using FileHelpers RunTime Records to create your definition you can populate same definition using reflection.

For example if you create a definition

        DelimitedClassBuilder cb = new DelimitedClassBuilder("Customers", ",");
        cb.AddField("StringField", "string");

        Type t = cb.CreateRecordClass();
        FileHelperEngine engine = new FileHelperEngine(t); 

Now you can use same type created by FileHelpers to populate your values as follows:

        object customClass = Activator.CreateInstance(t);
        System.Reflection.FieldInfo field = customClass.GetType().GetField("StringField", System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
        if (field != null)
        {
            field.SetValue(customClass, "StringValue");
        }

And then write it to file or string:

        string line = engine.WriteString(new object[] { customClass });


来源:https://stackoverflow.com/questions/2112924/dynamically-create-a-csv-file-with-filehelpers

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!