C#csv文件保存(通用版)

    /// <summary>
    /// 指定是否保存到文件中
    /// </summary>
    [AttributeUsage(AttributeTargets.Property)]
    public sealed class FileSaveAttribute : Attribute
    {
        public bool Save { get; set; }
        public FileSaveAttribute(bool isSave)
        {
            Save = isSave;
        }
    }

    /// <summary>
    /// 指定属性的格式化格式
    /// </summary>
    [AttributeUsage(AttributeTargets.Property)]
    public sealed class FormatAttribute : Attribute
    {
        public string Format { get; set; }
        public FormatAttribute(string format)
        {
            Format = format;
        }
    }

    public class FileSave<T>
    {
        public void CsvSave(string path, List<T> list, string title = null)
        {
            StringBuilder sb = new StringBuilder();
            if (title != null)
            {
                sb.AppendLine(title);
            }
            Type tInfo = typeof(T);
            List<object> listHeader = new List<object>();
            Dictionary<string, object> dictData = new Dictionary<string, object>();
            foreach (PropertyInfo p in tInfo.GetProperties())
            {
                string key = p.Name;
                if (tInfo.GetAttributes<FileSaveAttribute>(key, out object isSave))
                {
                    if (!(bool)isSave)
                    {
                        continue;
                    }
                }
                //不存在默认为保存
                tInfo.GetAttributes<DisplayNameAttribute>(key, out object displayName);
                listHeader.Add(displayName ?? key);
                dictData[key] = null;
            }
            sb.AppendLine(string.Join(",", listHeader));
            foreach (var model in list)
            {
                foreach (PropertyInfo p in tInfo.GetProperties())
                {
                    string key = p.Name;
                    if (dictData.ContainsKey(key))
                    {
                        dictData[key] = p.GetValue(model, null);
                    }
                }
                sb.AppendLine(string.Join(",", dictData.Values));
            }
            File.WriteAllText(path, sb.ToString(), Encoding.Default);
        }

    }

    public static class ExtentionMethod
    {
        /// <summary>
        /// 获取该类型中的属性有没有对应的特性值
        /// </summary>
        /// <typeparam name="T">特性类型</typeparam>
        /// <param name="type">查找的class类型</param>
        /// <param name="propertyName">class中的属性名称</param>
        /// <param name="value">out:特性值</param>
        /// <returns>是否存在该特性</returns>
        public static bool GetAttributes<T>(this Type type, string propertyName, out object value) where T : Attribute
        {
            value = default;
            Type attributeType = typeof(T);
            PropertyInfo propertyInfo = type.GetProperties().FirstOrDefault(p => p.Name == propertyName);
            if (propertyInfo != null)
            {
                Attribute attr = Attribute.GetCustomAttribute(propertyInfo, attributeType);
                if (attr != null)
                {
                    string attrPropertyName = string.Empty;
                    switch (attributeType.Name)
                    {
                        case "CategoryAttribute": attrPropertyName = "Category"; break;
                        case "DescriptionAttribute": attrPropertyName = "Description"; break;
                        case "DisplayNameAttribute": attrPropertyName = "DisplayName"; break;
                        case "ReadOnlyAttribute": attrPropertyName = "IsReadOnly"; break;
                        case "BrowsableAttribute": attrPropertyName = "Browsable"; break;
                        case "DefaultValueAttribute": attrPropertyName = "Value"; break;
                        case "FileSaveAttribute": attrPropertyName = "Save"; break;
                        case "FormatAttribute": attrPropertyName = "Format"; break;
                        default:
                            return false;
                    }
                    PropertyDescriptorCollection attrPropertys = TypeDescriptor.GetProperties(type);
                    var fs = attributeType.GetProperties();
                    PropertyInfo attrPropertyInfo = attributeType.GetProperty(attrPropertyName, BindingFlags.Instance | BindingFlags.Public | BindingFlags.CreateInstance);
                    value = attrPropertyInfo.GetValue(attrPropertys[propertyInfo.Name].Attributes[attributeType]);
                    return true;
                }
            }
            return false;
        }
    }

  • 1
    点赞
  • 6
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

Bridge_go

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值