CsvHelper支持List<T>

 

 

/// <summary>
    /// Csv帮助类
    /// </summary>
    public class CsvHelper
    {
        /// <summary>
        /// List<T>转换为Csv所支持的字符串
        /// </summary>
        /// <typeparam name="T">类型</typeparam>
        /// <param name="list">列表</param>
        /// <returns>转换后的字符串</returns>
        public static string ToCsvString<T>(IEnumerable<T> list) where T : class
        {
            var type = typeof(T);
            var props = type.GetProperties();
            StringBuilder sb = new StringBuilder();

            for (int i = 0; i < props.Length; i++)
            {
                var prop = props[i];
                if (i > 0)
                {
                    sb.Append(",");
                }

                sb.Append(prop.Name);
            }

            sb.AppendLine();
            if (list != null)
            {
                foreach (var obj in list)
                {
                    for (int i = 0; i < props.Length; i++)
                    {
                        var prop = props[i];
                        var propValue = prop.GetValue(obj, null);
                        if (i > 0)
                        {
                            sb.Append(",");
                        }

                        if (propValue == null)
                            sb.Append(string.Empty);
                        else
                            sb.Append(FomartCsvData(propValue.ToString()));
                    }

                    sb.AppendLine();
                }
            }

            return sb.ToString();
        }

        /// <summary>
        /// 字符串转义
        /// </summary>
        /// <param name="str">原字符串></param>
        /// <returns>转义后字符串</returns>
        private static string FomartCsvData(string str)
        {
            if (string.IsNullOrEmpty(str))
                return str;

            ////当表格内容有"双引号时,转换为两个""双引号,外面用双引号括起来
            if (str.Contains("\""))
            {
                str = str.Replace("\"", "\"\"");
            }

            ////当表格内容有,半角逗号、换行、空格、tab 等特殊字符时,外面使用双引号括起来。
            if (str.Contains(",") || str.Contains("\"") || str.Contains("\n") || str.Contains("\r") || str.Contains("\t") || str.Contains(" "))
            {
                str = string.Format("{0}{1}{0}", "\"", str);
            }

            return str ;
        }

    }

 

 

逗号,双引号转义参考下面链接

http://blog.csdn.net/zzx3q/article/details/7456710

http://www.cnblogs.com/batsing/p/csv1.html

posted @ 2016-11-02 15:37  zslm___  阅读(574)  评论(0编辑  收藏  举报