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

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

问题描述

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

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>();

写工人名单:

csv.WriteRecords(workerList);

如何将 customerField 字典映射到 Excel 表,以便键(字符串)是另一个列名,而值(对象)是该列的值.

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天全站免登陆