我想知道是否有任何方法让CSV阅读器读取CSV中的所有列(它们将具有相同的列名)。我得到一个An item with the same key has already been added错误。我希望这样做是可行的,因为我的逻辑是,如果存在类似的命名列,则生成一个数组,然后再为数组元素的每个实例编写进一步的逻辑。
最后一点是,即使有同名的列,我也希望能够读取所有的列。我使用一个自定义对象来保存名称值数据。因此,不必担心字典会导致相同的键存在错误。如果Lumen不支持它,那么我可以使用什么?我的CSV文件也有Json数据(带有双引号,逗号),我也需要处理这个问题。
发布于 2014-12-30 07:41:40
你把我搞糊涂了--我不知道有哪个CSV解析器能解释重复的列标题,而且我测试了其中很多。还有CSV解析器,它将为您提供原始的列数据,通过一些腿的工作,您可以使用它作为构建块,使您的数据进入更友好的状态。
这将返回一个Dictionary<string, List<string>>序列,每个记录一个,键为标头,列表为具有相同标题的所有列:
using System.IO;
using System.Collections.Generic;
using Ctl.Data;
static IEnumerable<Dictionary<string, List<string>>> ReadCsv(string filePath)
{
using (StreamReader sr = new StreamReader(filePath))
{
CsvReader csv = new CsvReader(sr);
// first read in the header.
if (!csv.Read())
{
yield break; // an empty file, break out early.
}
RowValue header = csv.CurrentRow;
// now the records.
while (csv.Read())
{
Dictionary<string, List<string>> dict =
new Dictionary<string, List<string>>(header.Count);
RowValue record = csv.CurrentRow;
// map each column to a header value
for (int i = 0; i < record.Count; ++i)
{
// if there are more values in the record than the header,
// assume an empty string as header.
string headerValue = (i < header.Count ? header[i].Value : null)
?? string.Empty;
// get the list, or create if it doesn't exist.
List<string> list;
if (!dict.TryGetValue(headerValue, out list))
{
dict[headerValue] = list = new List<string>();
}
// finally add column value to the list.
list.Add(record[i].Value);
}
yield return dict;
}
}
}我对Lumenworks还不太熟悉--它使用的是Ctl.Data,我知道它将允许格式化JSON数据和列中的任何其他奇怪之处,只要引用正确。(免责声明:我是Ctl.Data的作者)
发布于 2019-08-03 22:19:26
由于jonreis的支持,这在LumenWorks 4.0中得到了支持。
请参阅LumenWorks.Framework.Tests.Unit/IO/Csv/CsvReaderTest.cs
using (CsvReader csvReader = new CsvReader(new StringReader("Header,Header\r\nValue1,Value2"), true))
{
csvReader.DuplicateHeaderEncountered += (s, e) => e.HeaderName = $"{e.HeaderName}_{e.Index}";https://stackoverflow.com/questions/27701134
复制相似问题