使用CsvHelper仅将选定的列写入CSV文件 [英] Writing only selected columns to CSV-file using CsvHelper

查看:94
本文介绍了使用CsvHelper仅将选定的列写入CSV文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个小程序,可以从Web服务中获取数据.该程序获取JSON响应,将其映射到POCO,然后将对象写入CSV文件(自动映射).当我要求全部"数据集中的数据时,它可以完美工作,但是,如果我通过以下方式查询资源(通过OData):"$ select EmpNo,FirstName,LastName",则CSV编写器仍将写入所有列到CSV标头,例如"EmpNo,FirstName,LastName,Street,Address,City,Age"等,只需在没有数据的列中插入0(如果是int),false(如果是布尔值)或"(如果是字符串).

I have a little program that fetches data from a web service. The program takes the JSON response, maps it to POCOs and writes the objects to a CSV file (automapping). It works perfectly when I ask for "all" the data in the dataset, however, if I query the resource (via OData) like this: "$select EmpNo, FirstName, LastName", the CSV writer will still write all of the columns to the CSV header, e.g. "EmpNo, FirstName, LastName, Street, Address, City, Age" etc. and just insert 0 (if int), false(if boolean) or "" (if string) to the columns that have no data.

Web服务仅正确返回指定的列,所以这不是问题.我使用CsvHelper进行对象映射和CSV编写.(但是我愿意使用任何可以解决我的问题的方法)

The web service correctly returns only the specified columns, so that's not the issue. I use CsvHelper for the object mapping and CSV-writing. (But I'm open to using anything that can solve my problem)

如果我要在OData查询中要求的话,我只想将"EmpNo,FirstName,LastName"和列的数据写入CSV文件.

I'd like to only write "EmpNo, FirstName, LastName" and the columns' data to the CSV-file, if that's what I ask for in the OData query.

解决这个问题有什么好主意吗?

Any good ideas for solving this?

推荐答案

在不知道您使用的确切代码的情况下很难分辨.但是我的猜测是,当您编写对象列表时,您使用的是其中包含额外字段的模型,这些字段都是空的,因为您没有通过odata请求它们.

It is hard to tell without knowing the exact code you're using. But my guess is that when you write your list of objects you're using the model that has the extra fields in it, which are all empty because you didn't request them via odata.

如果只需要CsvHelper的子集,则可能要指定 CsvClassMap< T> ,这会将现有模型映射到所需的字段中

If you want just the subset with CsvHelper, you probably want to specify a CsvClassMap<T> and that will map your existing model into just the fields you want

在此处的CsvClassMap上有很多示例: http://joshclose.github.io/CsvHelper/

There are lots of examples on a CsvClassMap here: http://joshclose.github.io/CsvHelper/

write方法可能会重载采用类映射的方法.

The write method will likely have a method overload that will take a classmap.

这篇关于使用CsvHelper仅将选定的列写入CSV文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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