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 == ) return null; //get type from 0th member
Type t = list[].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设置列名

CVS导出&&自定义Attribute的使用的更多相关文章

  1. XsdGen:通过自定义Attribute与反射自动生成XSD

    前言 系统之间的数据交互往往需要事先定义一些契约,在WCF中我们需要先编写XSD文件,然后通过自动代码生成工具自动生成C#对象.对于刚刚接触契约的人来说,掌握XMLSpy之类的软件之后确实比手写XML ...

  2. 2.C#自定义Attribute

    阅读目录    一:C#自定义Attribute    二:AttributeUsageAttribute中的3个属性(Property)中的AttributeTargets   三:Attribut ...

  3. 自定义Attribute 服务端校验 客户端校验

    MVC 自定义Attribute 服务端校验 客户端校验/* GitHub stylesheet for MarkdownPad (http://markdownpad.com) *//* Autho ...

  4. C#自定义Attribute值的获取与优化

    C#自定义Attribute值的获取是开发中会经常用到的,一般我们的做法也就是用反射进行获取的,代码也不是很复杂. 1.首先有如下自定义的Attribute [AttributeUsage(Attri ...

  5. .net c#获取自定义Attribute

    前言: 在c#开发中,有时候我们需要读取 Attribute中的信息(关于Attribute , 我自己把他理解成一个可以为类,属性标记的东西,这个标记可以为你提供一些关于类,方法,属性的额外信息) ...

  6. 【Q2D】如何导出自定义C++类给框架使用

    本文基于Quick cocos2d x这个游戏框架,为了行文流畅,后面都简称Q2D 导出自定义c++类给项目使用已经有了现成的例子了 详见:http://quick.cocos.org/?p=235 ...

  7. 转:C#制作ORM映射学习笔记一 自定义Attribute类

    之前在做unity项目时发现只能用odbc连接数据库,感觉非常的麻烦,因为之前做web开发的时候用惯了ORM映射,所以我想在unity中也用一下ORM(虽然我知道出于性能的考虑这样做事不好的,不过自己 ...

  8. 【MVC 笔记】MVC 自定义 Attribute 属性中的猫腻

    原想在 MVC Action 上加一个自定义 Attribute 来做一些控制操作,最先的做法是在自定 Attribute 中定义一个属性来做逻辑判断,可惜事与愿违,这个属性值居然会被缓存起来,于是于 ...

  9. 通过自定义Attribute及泛型extension封装数据验证过程

    需求来源: 在日常工作中,业务流程往往就是大量持续的数据流转.加工.展现过程,在这个过程中,不可避免的就是数据验证的工作.数据验证工作是个很枯燥的重复劳动,没有什么技术含量,需要的就是对业务流程的准确 ...

随机推荐

  1. Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' on a null

    1.Android Studio报错 Attempt to invoke interface method 'boolean java.util.List.add(java.lang.Object)' ...

  2. MySQL · 功能分析 · 5.6 并行复制实现分析

    背景 我们知道MySQL的主备同步是通过binlog在备库重放进行的,IO线程把主库binlog拉过去存入relaylog,然后SQL线程重放 relaylog 中的event,然而这种模式有一个问题 ...

  3. 003-spring cloud gateway-概述、Route模型、网关初始化配置过程、基本原理

    一.概述 网关服务核心是将进入的请求正确合理的路由到下层具体的服务进行业务处理,由此可见网关服务的核心就是路由信息的构建. Spring Cloud Gateway旨在提供一种简单而有效的方式来路由到 ...

  4. clientHeight , scrollHeight , offsetHeight之间的区别

    clientHeight:元素客户区的大小,指的是元素内容及其边框所占据的空间大小(经过实践取出来的大多是视口大小) scrollHeight: 滚动大小,指的是包含滚动内容的元素大小(元素内容的总高 ...

  5. 智能指针 - 现代C++新特性总结

    C++98中的智能指针通过一个模板类auto_ptr来实现,new操作符返回的指针可以交由它来管理,程序员不用再显式的调用delete,这在一定程度上避免了堆内存忘记释放的问题:不过auto_ptr有 ...

  6. tomcat访问

    1:html页面或者需要访问的对象需要放置到webapps/ROOT下面既可以  http://localhost:8080/直接访问 2:

  7. Docker 后台进程参数-------更改Docker运行根目录的方法

    参数 介绍 --api-enable-cors=false 远程API调用. -b, --bridge="" 桥接一个系统上的网桥设备到 Docker 容器里,当使用 none 可 ...

  8. PAT 1067 Sort with Swap[难]

    1067 Sort with Swap(0,*) (25)(25 分) Given any permutation of the numbers {0, 1, 2,..., N-1}, it is e ...

  9. Xcode 快捷键及代码格式化

    按住apple键点击类名就可以定位到这个类中查看相关定义(在日后的开发中我们会经常这么来做,毕竟要记住iOS开发中所有的API是不现实的,有些API我们可以通过这种方法来查找) PS:下面都是网上百度 ...

  10. UNDFTD x Nike Air Max 97 OG Black

    The UNDFTD x Nike Air Max 97 OG Black is releasing way sooner than anticipated. This collaborative r ...