首先添加引用: Nuget包里搜索CsvHelper,作者是Josh Close ,下载量蛮高的有111M
创建一个测试类
public class Ad
{
public string Name { get; set; }
public string Description { get; set; }
}
//赋值
Ad a = new Ad();
a.Name = "CSDN";
a.Description = "我爱你";
//调用并写入csv
List<Ad> records = new List<Ad>();
records.Add(a);
//写CSV文件
using (var writer = new StreamWriter("D:\\1.csv",false,Encoding.UTF8) )
using (var csv = new CsvWriter(writer, CultureInfo.InvariantCulture))
{
csv.WriteRecords(records);
}
分享一个自己写的方法
public class CsvExportHelper
{
public static bool CreateAdvExcel<T>(IList<T> lt, string path)
{
try
{
StringBuilder builder = new StringBuilder();
System.Reflection.PropertyInfo[] myPropertyInfo = lt.First().GetType().GetProperties(System.Reflection.BindingFlags.Public | System.Reflection.BindingFlags.Instance);
int i = 0, j;
for (i = 0, j = myPropertyInfo.Length; i < j; i++)
{
System.Reflection.PropertyInfo pi = myPropertyInfo[i];
string headname = pi.Name;//单元格头部
var attrs = pi.GetCustomAttributes(typeof(DisplayNameAttribute), true);
if (attrs != null && attrs.Count() > 0)
{
headname = ((DisplayNameAttribute)attrs[0]).DisplayName;
}
builder.Append(headname);
builder.Append("\t");
}
builder.Append("\n");
foreach (var t in lt)
{
if (lt == null)
{
continue;
}
for (i = 0, j = myPropertyInfo.Length; i < j; i++)
{
System.Reflection.PropertyInfo pi = myPropertyInfo[i];
string str = string.Format("{0}", pi.GetValue(t, null)).Replace("\n", "");
if (str == "")
{
builder.Append("\t");
}
else
{
builder.Append(str + "\t");//横向跳到另一个单元格
}
}
builder.Append("\n");//换行
}
using (StreamWriter sw = new StreamWriter(path, false, System.Text.Encoding.GetEncoding("GB2312")))
{
sw.Write(builder.ToString());//输出
sw.Flush();
sw.Close();
}
return true;
}
catch (Exception ex)
{
Console.WriteLine(ex.Message);
return false;
}
}
}