如何将我的列表正确导出为 csv 文档?



所以我得到了一个类型Item的集合,我正在尝试将值映射到CSV文件,但它无法正常工作。它很好地映射了这些值。ItemNameSubTitlePriceConditionQuantityQuantitySoldProductImage,然后它不再映射。我认为这是因为另外两个属性是集合。ListDictionary

这就是我目前映射它的方式。

using (var mem = new MemoryStream())
using (var writer = new StreamWriter(mem))
using (var csvWriter = new CsvWriter(writer, CultureInfo.CurrentCulture))
{
csvWriter.Configuration.Delimiter = ",";
csvWriter.Configuration.HasHeaderRecord = true;
csvWriter.Configuration.AutoMap<Item>();
csvWriter.WriteHeader<Item>();
csvWriter.WriteRecords(Products);
writer.Flush();
var result = Encoding.UTF8.GetString(mem.ToArray());
File.WriteAllText("Items.csv", result);
Console.WriteLine(result);
}

问题似乎是 CsvHelper 没有正确映射字典,这使得这变得更加困难。我已经读到让它动态或类似的东西可能会有所帮助吗?因为它使用ExpandoObject?https://stackoverflow.com/a/22997553/11966121

现在的问题是我不知道如何正确执行此操作,我是否单独映射所有字段?

这也是模型

class Item
{
public string ItemName { get; set; }
public string SubTitle { get; set; }
public string Price { get; set; }
public string Condition { get; set; }
public Dictionary<string, List<string>> SKU { get; set; }
public string Quantity { get; set; }
public string QuantitySold { get; set; }
public string ProductImage { get; set; }
public List<string> ProductImages { get; set; }
}

您应该能够使用ClassMapConvertUsing来创建它。

public class Program
{
static void Main(string[] args)
{
var products = new List<Item>
{
new Item
{
ItemName = "Item1",
SubTitle = "Item1 Sub Title",
Price = "45",
Condition = "Good",
SKU = new Dictionary<string, List<string>>
{
{ "1234", new List<string>{ "First", "second"} },
{ "5678", new List<string>{ "third", "fourth"} }
},
Quantity = "2",
QuantitySold = "5",
ProductImage = "image",
ProductImages = new List<string>{"Image1", "Image2", "Image3"}
}
};
using (var csvWriter = new CsvWriter(Console.Out, CultureInfo.CurrentCulture))
{
csvWriter.Configuration.Delimiter = ",";
csvWriter.Configuration.RegisterClassMap<ItemClassMap>();
csvWriter.WriteRecords(products);
}
Console.ReadKey();
}
}
public class Item
{
public string ItemName { get; set; }
public string SubTitle { get; set; }
public string Price { get; set; }
public string Condition { get; set; }
public Dictionary<string, List<string>> SKU { get; set; }
public string Quantity { get; set; }
public string QuantitySold { get; set; }
public string ProductImage { get; set; }
public List<string> ProductImages { get; set; }
}
public class ItemClassMap : ClassMap<Item>
{
public ItemClassMap()
{
Map(m => m.ItemName);
Map(m => m.SubTitle);
Map(m => m.Price);
Map(m => m.Condition);
Map(m => m.SKU).ConvertUsing(row =>
{
var output = string.Empty;
for (int count = 0; count < row.SKU.Count; count++)
{
var kvp = row.SKU.ElementAt(count);
output += kvp.Key + ":" + string.Join(",", kvp.Value);
if (count < row.SKU.Count - 1)
{
output += " ";
}
}
return output;
});
Map(m => m.Quantity);
Map(m => m.QuantitySold);
Map(m => m.ProductImage);
Map(m => m.ProductImages).ConvertUsing(row => string.Join(",", row.ProductImages));
}
}

相关内容

  • 没有找到相关文章

最新更新