码迷,mamicode.com
首页 > 其他好文 > 详细

CVS导出&&自定义Attribute的使用

时间:2017-08-07 22:16:37      阅读:244      评论:0      收藏:0      [点我收藏+]

标签:val   ati   width   env   activator   svc   replace   ops   text   

1.cvs导出:List转为byte[]

    /// <summary>
    ///  CvsExport帮助类
    /// </summary>
    public static class CvsExportHelper
    {
        /// <summary>
        /// Creates the CSV from a generic list.
        /// </summary>;
        /// <typeparam name="T"></typeparam>;
        /// <param name="list">The list.</param>;
        public static byte[] CreateCSVFromGenericList<T>(List<T> list)
        {
            if (list == null || list.Count == 0) return null;


            //get type from 0th member
            Type t = list[0].GetType();
            string newLine = Environment.NewLine;
            MemoryStream output = new MemoryStream();
            using (var sw = new StreamWriter(output, new UTF8Encoding(true)))// 用true来指定包含bom
            {
                //make a new instance of the class name we figured out to get its props
                object o = Activator.CreateInstance(t);
                //gets all properties
                PropertyInfo[] props = o.GetType().GetProperties();

                //foreach of the properties in class above, write out properties
                //this is the header row
                foreach (PropertyInfo pi in props)
                {
                    var attributes = pi.GetCustomAttributes(false);
                    var columnMapping = attributes
                        .FirstOrDefault(a => a.GetType() == typeof(CSVColumnAttribute));
                    if (columnMapping != null)
                    {
                        var mapsto = columnMapping as CSVColumnAttribute;
                        sw.Write(mapsto.Name + ",");
                    }
                    else
                    {
                        sw.Write(pi.Name + ",");
                    }
                }
                sw.Write(newLine);

                //this acts as datarow
                foreach (T item in list)
                {
                    //this acts as datacolumn
                    foreach (PropertyInfo pi in props)
                    {
                        //this is the row+col intersection (the value)
                        string whatToWrite =
                            Convert.ToString(item.GetType()
                                                 .GetProperty(pi.Name)
                                                 .GetValue(item, null))
                                .Replace(,,  ) + ,;

                        sw.Write(whatToWrite);

                    }
                    sw.Write(newLine);
                }
                sw.Flush();
            }
            byte[] bytesInStream = output.ToArray(); // simpler way of converting to array
            output.Close();
            return bytesInStream;
        }
    }

2.前端调用

        /// <summary>
        ///  CSV Export
        /// </summary>
        /// <param name="r"></param>
        /// <returns></returns>
        [HttpPost]
        [ActionName("CSVExport")]
        public ActionResult CSVExport(ExportDSVRequest r)
        {
            string fileName = string.Format("CRMInfo-{0}.csv", Guid.NewGuid().ToString());
            byte[] result = null;
            if (string.IsNullOrWhiteSpace(r.JsonData)) {
               return Redirect("~/report/list");//返回上一页
            }

            var billsResult = JsonHelper.DeserializeJsonToList<AccountDailyMarginCSV>(r.JsonData);
 
            result = CvsExportHelper.CreateCSVFromGenericList(billsResult);
            return File(result, "text/csv", fileName);
        }    

自定义attribute

    /// <summary>
    /// CSV列名Attribute
    /// </summary>
    public class CSVColumnAttribute : Attribute
    {
        /// <summary>
        /// Name
        /// </summary>
        public string Name { get; }
        /// <summary>
        /// set name
        /// </summary>
        /// <param name="name"></param>
        public CSVColumnAttribute(string name)
        {
            this.Name = name;
        }
    }

attribute使用:对List<T>中的T设置列名

技术分享

 

CVS导出&&自定义Attribute的使用

标签:val   ati   width   env   activator   svc   replace   ops   text   

原文地址:http://www.cnblogs.com/panpanwelcome/p/7301137.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!