using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
namespace UpLoadExcel
{
class Program
{
static void Main(string[] args)
{
//标题
var titles = new Dictionary<string, string>();
titles.Add("name", "姓名");
titles.Add("age", "年龄");
titles.Add("sex", "性别");
//数据源
var list = new List<Student>();
list.Add(new Student {
name="张三",age=18,sex="男"
});
list.Add(new Student
{
name = "李四",
age = 18,
sex = "女"
});
//表格名称
var fileName = "学生信息";
//保存路径
var fileurl = "D:/";
//生成csv文件并保存
bool bol = SaveCsv(titles, list, fileName, fileurl);
}
/// <summary>
///导出csv文件
/// </summary>
/// <param name="titles">列名</param>
/// <param name="list">导出数据</param>
/// <param name="fileName">文件名字</param>
/// <param name="fileurl">文件地址</param>
/// <returns></returns>
public static bool SaveCsv<T>(Dictionary<string, string> titles, List<T> list, string fileName, string fileurl)
{
bool flag = true;
try
{
StringWriter swCSV = new StringWriter();
if (list.Count > 0)
{
string titleStr = string.Empty;
List<System.Reflection.PropertyInfo> myPro = new List<System.Reflection.PropertyInfo>();
Type myType = list[0].GetType();
foreach (string ckey in titles.Keys)
{
titleStr += titles[ckey] + ",";
//c++;
System.Reflection.PropertyInfo p = myType.GetProperty(ckey);
if (p != null)
{
myPro.Add(p);
}
}
//列名
swCSV.WriteLine(titleStr.Substring(0, titleStr.Length - 1));
//遍历datatable导出数据
foreach (T obj in list)
{
StringBuilder sbText = new StringBuilder();
foreach (System.Reflection.PropertyInfo p in myPro)
{
if (p.GetValue(obj, null) != null)
{
sbText.Append(p.GetValue(obj, null).ToString().Replace(",", ",") + ",");
}
else
{
sbText.Append(",");
}
}
sbText.Remove(sbText.Length - 1, 1);
swCSV.WriteLine(sbText.ToString());
}
}
//生成文件并保存文件
string url = fileurl + "fileupload\\" + fileName + ".csv";//要存储的路径
if (!Directory.Exists(fileurl + "fileupload\\"))
{
Directory.CreateDirectory(fileurl + "fileupload\\");
}
StreamWriter sw = new StreamWriter(url, false, System.Text.Encoding.UTF8);//把文件作为文件流保存在固定的路径
sw.Write(swCSV.ToString());// 文件流写出
sw.Flush();//判断是否有文件,如果有则删除
sw.Dispose();//释放流的资源
swCSV.Close();
swCSV.Dispose();
}
catch (Exception ex)
{
flag = false;
}
return flag;
}
}
/// <summary>
/// 学生类
/// </summary>
public class Student
{
public string name { get; set; }
public int age { get; set; }
public string sex { get; set; }
}
}
简单的List集合导出为Excel
最新推荐文章于 2024-01-30 16:12:15 发布