Open nfplee opened 1 year ago
why you've closed it? have you found the solution to get expected result Id,Name,Attribute1,Attribute2
?
I have the same problem now.
Hi @b-maslennikov,
I'm not sure why I closed this out. For now I got around this by doing the following:
using (var writer = new StreamWriter("file.csv"))
using (var csv = new CsvWriter(writer, new CsvConfiguration(CultureInfo.InvariantCulture) {
HasHeaderRecord = false
})) {
csv.Context.RegisterClassMap<ProductViewModelMap>();
csv.WriteHeader<ProductViewModel>(["Attribute1", "Attribute2"]);
await csv.WriteRecordsAsync(products);
}```
Here's my extension method to manually write the header:
```cs
public static class CsvWriterExtensions {
public static void WriteHeader<T>(this CsvWriter csv, IEnumerable<string> attributeNames) {
foreach (var property in typeof(T).GetProperties().Where(p => p.Name != "Attributes")) {
csv.WriteField(property.Name);
}
foreach (var attributeName in attributeNames) {
csv.WriteField(attributeName);
}
csv.NextRecord();
}
}
My temporary solution: replace classmap with method that converts T to dynamic. + WriteDynamicHeader() It would great to have requested functionality...
Is it possible to create a CSV file which has a dictionary collection, where each key in the dictionary is mapped as separate column headers. This is the best I've come up with so far:
However this produces:
But I would like:
I've tried numerous things but nothing seems to work. Ideally I'd like to use a
ClassMap
instead of writing the raw contents as I think this should be supported out of the box.