CsvHelper

 namespace CsvHelper
 {
    class Program
    {
        static void Main(string[] args)
        {
            string userProfile = Environment.GetFolderPath(Environment.SpecialFolder.UserProfile);
            string path1 = Path.Combine(userProfile, @"test1.csv");
            string path2 = Path.Combine(userProfile, @"test2.csv");
 
            var records = new List<object>()
                { 
                    new { id = 123, name = "abc"},
                    new { id = 456, name = "xyz"},
                };
 
            using (TextWriter writer = File.CreateText(path1)) {
                var csv = new CsvWriter(writer);
                csv.Configuration.HasHeaderRecord = false;
                csv.WriteRecords(records);
            }
 
            var records2 = new List<User>() {
                new User() {Id = 100, Name = "a\"bc", Age = 10},
                new User() {Id = 101, Age = 30},
                new User() {Id = 102, Name = "sml"},
            };
 
            AutoMapper.Mapper.CreateMap<User, CustomUser>();
            var records3 = new List<CustomUser>();
            foreach (var r in records2) {
                records3.Add(AutoMapper.Mapper.Map<CustomUser>(r));
            }
 
            using (TextWriter writer = File.CreateText(path2)) {
                var csv = new CsvWriter(writer);
                csv.Configuration.RegisterClassMap<UserMap>();
                csv.WriteRecords(records3);
            }
 
            Console.WriteLine("CsvHelper");
            Console.ReadKey();
        }
    }
 
    class User
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
    }
 
    class CustomUser
    {
        public int Id { get; set; }
        public string Name { get; set; }
        public int Age { get; set; }
        public string AgeDisp
        {
            get
            {
                if (Age == 0) {
                    return "No Age";
                }
                else {
                    return Age.ToString();
                }
            }
        }
    }
 
    class UserMap : CsvClassMap<CustomUser>
    {
        public override void CreateMap()
        {
            Map(m => m.Id).Name("User Id").Index(0);
            Map(m => m.Name).Index(1).Default("No name");
            Map(m => m.AgeDisp).Index(2).Default("No Age");
        }
    }
 }

参考

http://joshclose.github.io/CsvHelper/


トップ   新規 一覧 検索 最終更新   ヘルプ   最終更新のRSS