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. sql优化 慢查询分析

    查询速度慢的原因很多,常见如下几种 SQL慢查询分析 转自:https://www.cnblogs.com/firstdream/p/5899383.html 1.没有索引或者没有用到索引(这是查询慢 ...

  2. 定时任务,AlarmManager使用

    CoderLt   定时任务,AlarmManager使用 项目需要:实现一个定时提醒的功能 查阅资料知道,需要使用AlarmManager AlarmManager介绍: AlarmManager是 ...

  3. Tomcat项目部署的三种方法

    第一种方法如下:直接把我们的项目文件夹放到tomcat里面,在这里我自己做的是一个测试项目oa,如图 启动tomcat,打开浏览器,输入localhost/oa  即可打开你的文件,注意 :访问的时候 ...

  4. 3.cassandra遇到内存占用过高的问题

    目前cssandra的内存分配如下: https://docs.datastax.com/en/cassandra/2.1/cassandra/operations/ops_tune_jvm_c.ht ...

  5. PHPExcel使用-使用PHPExcel导入文件

    导入步骤: 1. 实例化excel读取对象 2. 加载excel文件 ----------------> ( 1>. 全部加载. 2>. 选择加载. ) 3. 读取excel文件 - ...

  6. KMP(http://acm.sdut.edu.cn/sdutoj/problem.php?action=showproblem&problemid=2772)

    #include <stdio.h>#include <string.h>#include <stdlib.h>char a[1000001],b[1000001] ...

  7. Andrew Ng-ML-第十三章-支持向量机

    1.从代价函数谈起SVM 图一 根据将y=0||y=1,得到逻辑回归的代价函数,那么SVM和其代价函数是相似的,只不过是引入了cost0与cost1,并且自变量使用了theta_T*x(i),并且由于 ...

  8. 从Maven仓库中导出jar包

    从Maven仓库中导出jar包:进入工程pom.xml 所在的目录下,输入以下命令:mvn dependency:copy-dependencies -DoutputDirectory=lib更简单的 ...

  9. Javascript-蔬菜运算价格

    <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8&quo ...

  10. sql server 中的分区函数用法(partition by 字段)

    partition  by关键字是分析性函数的一部分,它和聚合函数不同的地方在于它能返回一个分组中的多条记录,而聚合函数一般只有一条反映统计值的记录,partition  by用于给结果集分组,如果没 ...