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. 006-Redis 发布订阅

    Redis 发布订阅(pub/sub)是一种消息通信模式:发送者(pub)发送消息,订阅者(sub)接收消息. Redis 客户端可以订阅任意数量的频道. 下图展示了频道 channel1 , 以及订 ...

  2. caffe学习记录

    结论: caffe网络的prototxt训练与测试的时候用的是不同的,训练的时候用的prototxt里面有test只是为了测试网络的训练程度,里面的测试集是验证集,并不是真正我们测试的时候用的网络定义 ...

  3. 既生list何生tuple

    python中list是可以修改的;若要创建一系列不可修改的元素时,就需要tuple. 用 tuple 的好处: 1.tuple 比 list 操作速度快.如果您定义了一个值的常量集,并且唯一要用它做 ...

  4. Py-lamda表达式学习【转载】

    转自:https://blog.csdn.net/zjuxsl/article/details/79437563 1.语法定义 在Python中,lambda的语法是唯一的.其形式如下: lambda ...

  5. [参考资料] 80个Python经典资料(教程+源码+工具)汇总

    AD : 2018重磅地面课程<机器读心术之语音识别前沿实战特训营>,迈向人工智能新高度 [专题推荐]Python系列英文原版电子书 http://down.51cto.com/zt/10 ...

  6. [LeetCode] 195. Tenth Line_Easy tag: Bash

    Given a text file file.txt, print just the 10th line of the file. Example: Assume that file.txt has ...

  7. H2O.ai初步使用

    1.官网下载最新稳定版,https://www.h2o.ai/download/ ,如果点击下载无反应,请使用ie浏览器 2.解压h2o-3.18.0.10.zip到目录h2o-3.18.0.10 3 ...

  8. fafu 1411

    想了好久都没想到怎么去判断当分类dp的时候大于或者等于要求的 值时应该怎么半 后来经过停了 qlx的想法 然后就 敲了出来 这题说的是 一个整数 分解成几个素数的和  按这个数的含有的最大素数 进行排 ...

  9. VS添加节点

    很喜欢添加节点来减少代码的长度,方便阅读:VS快捷键和相关设置

  10. python 读取二进制数据到可变缓冲区中

    想直接读取二进制数据到一个可变缓冲区中,而不需要做任何的中间复制操作.或者你想原地修改数据并将它写回到一个文件中去. 为了读取数据到一个可变数组中,使用文件对象的readinto() 方法.比如 im ...