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