zoukankan      html  css  js  c++  java
  • CVS导出&&自定义Attribute的使用

    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);
            }    
    

    导出至特定路径

                string fileName = string.Format("CRMInfo-{0}.csv", Guid.NewGuid().ToString());
                string content = log.ToString();
                string dir = Directory.GetCurrentDirectory();
                string fullName = Path.Combine(dir, fileName);
                if (File.Exists(fullName)) File.Delete(fullName);
                using (FileStream fs = new FileStream(fullName, FileMode.CreateNew, FileAccess.Write))
                {
                    StreamWriter sw = new StreamWriter(fs, Encoding.Default);
                    sw.Flush();
                    sw.Write(content);
                    sw.Flush();
                    sw.Close();
                }    
    

      

    自定义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设置列名

  • 相关阅读:
    数据结构图文解析之:哈夫曼树与哈夫曼编码详解及C++模板实现
    数据结构图文解析之:二叉堆详解及C++模板实现
    数据结构图文解析之:树的简介及二叉排序树C++模板实现.
    数据结构图文解析之:队列详解与C++模板实现
    数据结构图文解析之:栈的简介及C++模板实现
    数据结构图文解析之:数组、单链表、双链表介绍及C++模板实现
    C++ 顺序容器基础知识总结
    细说new与malloc的10点区别
    C++ 异常机制分析
    C++编译期多态与运行期多态
  • 原文地址:https://www.cnblogs.com/panpanwelcome/p/7301137.html
Copyright © 2011-2022 走看看