fin*_*ook 10 c# csv export-to-csv csvhelper
我正在尝试使用CsvHelper库的ConvertUsing
方法(v 2.4.0).
我已经阅读了有关ConvertUsing的文档但无法使其工作.
我正在使用一个简单的类:
public class Test
{
public long Id { get; set; }
public string Title { get; set; }
}
Run Code Online (Sandbox Code Playgroud)
有了这个ClassMap
:
public class TestClassMap : CsvClassMap<Test>
{
public override void CreateMap()
{
Map(m => m.Id).Name("id").ConvertUsing(row => 11111);
Map(m => m.Title).Name("title").ConvertUsing(row => row.GetField("title") + " 123");
}
}
Run Code Online (Sandbox Code Playgroud)
我使用这些代码的代码创建了一个类的实例,然后将其写入CSV:
var test = new Test() { Id = 99, Title = "Test title" };
using (var streamWriter = new StreamWriter("test.csv"))
{
var csv = new CsvWriter(streamWriter);
csv.Configuration.RegisterClassMap<TestClassMap>();
csv.WriteRecord(test);
}
Run Code Online (Sandbox Code Playgroud)
但是输出文件test.csv
始终采用以下格式:
id,title
99,Test title
Run Code Online (Sandbox Code Playgroud)
我正在寻找的输出是:
id,title
11111,Test title 123
Run Code Online (Sandbox Code Playgroud)
而且ConvertUsing
被忽略了.我试过只转换Id
,只有转换Title
,但这也不起作用.
我出错的任何想法?
我有类似的需求,这是我在将内容保存到csv文件之前修改内容所做的.
我有一个名为StringNormalizer的自定义类,它实现了CsvHelper.TypeConversion.ITypeConverter接口.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using CsvHelper.TypeConversion;
namespace MyNamespaceInHere {
public class StringNormalizer : ITypeConverter {
public bool CanConvertFrom(Type type) {
if (type == typeof(string)) return true;
return false;
}
public bool CanConvertTo(Type type) {
if (type == typeof(string)) return true;
return false;
}
public object ConvertFromString(TypeConverterOptions options, string text) { return normalize(text); }
public string ConvertToString(TypeConverterOptions options, object value) {
if (value == null) return string.Empty;
if (value.GetType() == typeof(string)) {
string str = (string)value;
return normalize(str);
}
return string.Empty;
}
public string normalize(string field) {
// Do stuff in here and return normalized string
return field + " just a sample";
}
}
}
Run Code Online (Sandbox Code Playgroud)
然后在我已定义映射的主程序中,我就像这样使用它
public sealed class ConMap : CsvClassMap<Contact> {
public override void CreateMap() {
Map(m => m.FirstName).Name("FirstName").TypeConverter<StringNormalizer>();
}
}
Run Code Online (Sandbox Code Playgroud)
因此保存到csv的所有内容都是"运行"我的字符串规范化程序.
归档时间: |
|
查看次数: |
5278 次 |
最近记录: |