.NET 泛型集合数据写CSV文件

1.功能类

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.IO;
using System.Linq;
using System.Reflection;
using System.Text;
using System.Threading.Tasks;

namespace Infrastructure
{
    public static class FileExtensions
    {
        public static bool EnsureDirectory(string path)
        {
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            return true;
        }

        public static bool CreateFile(string folder, string fileName, string fileExtension)
        {
            EnsureDirectory(folder);
            string filePath = Path.Combine(folder, string.Format("{0}.{1}",fileName, fileExtension));
            using (FileStream fileStream = new FileStream(filePath, FileMode.Create))
            {}
            return true;
        }

        public static bool SaveToCsv<T>(IEnumerable<T> array, string filePath)
        {
            bool flag = true;
            try
            {
                StringBuilder stringBuilderColumn = new StringBuilder();
                StringBuilder stringBuilderValue = new StringBuilder();

                Type type = typeof (T);
                object obj = Activator.CreateInstance(type);
                PropertyInfo[] props = type.GetProperties(BindingFlags.Public|BindingFlags.Instance);

                props.ToList().ForEach(x => stringBuilderColumn.Append(string.Format("{0},",x.Name)));
                stringBuilderColumn.Remove(stringBuilderColumn.Length - 1, 1);

                using (StreamWriter streamWriter = new StreamWriter(filePath))
                {
                    streamWriter.WriteLine(stringBuilderColumn);
                    array.ToList().ForEach(x =>
                    {
                        stringBuilderValue.Remove(0, stringBuilderValue.Length);
                        foreach (PropertyDescriptor pd in TypeDescriptor.GetProperties(typeof (T)))
                        {
                            stringBuilderValue.Append(string.Format("{0},",pd.GetValue(x) == null ? pd.GetValue(x) : pd.GetValue(x).ToString().Replace(',', ',')));
                        }
                        stringBuilderValue.Remove(stringBuilderValue.Length - 1, 1);
                        streamWriter.WriteLine(stringBuilderValue);
                    });
                }
            }
            catch
            {
                flag = false;
            }
            return flag;
        }
    }
}
2.调用方式

List<T> items = new List<T>();

xxx //为items集合赋值

string filePath = xxx;//文件存储路径

FileExtensions.SaveToCsv(items,filePath);//调用方法

posted @ 2019-10-25 17:46  jeff151013  阅读(247)  评论(0编辑  收藏  举报