使用csvHelper动态创建列 [英] Dynamic creation of columns using csvHelper

查看:268
本文介绍了使用csvHelper动态创建列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个工作人员,具有从服务器获取的各种字段.我正在使用CSVHelper包将此类转换为Excel工作表. 工人的字段如:

I have a worker with various fields that are fetched from server. I am using CSVHelper package to convert this class to an excel sheet. Worker has Fields like :

class Worker
{ 
    string name;
    string phone;
    string age;
    Dictionary<string,object> customerField;
}

我可以映射姓名,电话,电话号码

I can map the name, phone, number like

class WorkerMap : CsvClassMap<Worker>
{
    public WorkerMap()
    {
        Map(m => m.name);
        Map(m => m.phone);
        Map(m => m.age);
    }
}

然后我通过以下方式生成地图:

And I generate the map by :

csv.Configuration.RegisterClassMap<WorkerMap>();

通过以下方式写出工人名单:

Write the list of workers by :

csv.WriteRecords(workerList);

如何将customerField字典映射到excel工作表,以使Key(字符串)是另一个列名,而value(对象)是该列的值.

How can I map the customerField dictionary to the excel sheet such that the Key (string) is another column name and the value(object) is the value of the column.

CSVHelper是否可以帮助我们在运行时执行此操作.我浏览了文档.找不到对我有用的东西.

Does CSVHelper help us do it at runtime. I looked through the documentation. Couldn't find anything that worked for me.

推荐答案

我认为目前不支持编写字典.一方面,CsvHelper很难知道要写什么头.幸运的是,手动使用CsvWriter一次写入一个字段并不太复杂.如果我们假设每个Worker在customerField中具有相同的键,那么您的代码可能看起来像这样.

I don't think that writing a dictionary is supported at this time. For one thing, CsvHelper would have a difficult time knowing what headers to write. Fortunately, it's not too complex to use CsvWriter manually, writing a field at a time. If we assume that each Worker has the same keys in customerField then your code might look something like this.

var firstWorker = workerList.First();
var keys = firstWorker.customerField.Keys.ToList();

var headers = new []{ "name", "phone", "age"}.Concat(keys).ToList();
var csv = new CsvWriter( textWriter );

// Write the headers
foreach( var header in headers )
{
    csv.WriteField(header);
}
csv.NextRecord();

// Write the rows
foreach( var item in workerList)
{
    csv.WriteField(item.name);
    csv.WriteField(item.phone);
    csv.WriteField(item.age);
    var dict = worker.customerField;
    foreach (var key in keys)
    {
        csv.WriteField(dict[key]);
    }
    csv.NextRecord();
}

此代码未经测试,但是应该可以使您非常接近所需的行为.如果customerField词典关键字在列表中不一致,则代码会稍微复杂一些,但仍然可以解决.

This code is untested, but should get you pretty close to the behavior you need. If the customerField dictionary keys are not consistent in the list then the code would be a bit more complicated but it's still solvable.

这篇关于使用csvHelper动态创建列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆