//通过构建Excel模版,填写数据进行导入
//建立一个学生数据
Student dd = new Student();
List a = dd.GetStudentData();
//目录路径
string PATH = @“D:\123.xls”;
//调用建表方法
DataExport(a, PATH);
//构建Excel模版,填写数据进行导入类方法
public static void DataExport<T>(List<T> list, string filePath)
{
if (list.Count > 0)
{
//用于创建文件
using (FileStream fileStream = new FileStream(filePath, FileMode.OpenOrCreate))
{
//用于写入内容
using (StreamWriter streamWriter = new StreamWriter(new BufferedStream(fileStream), Encoding.Default))
{
//表头
string tbhead = String.Empty;
var entity = list[0].GetType();
PropertyInfo[] piList = entity.GetProperties();
foreach (PropertyInfo pi in piList)
{
tbhead += pi.Name + "\t";
}
//取完表头,换行
tbhead = tbhead.Substring(0, tbhead.Length - 1) + "\n";
//表头写入
streamWriter.Write(tbhead);
foreach (var v in list)
{
string tbbody = String.Empty;
StringBuilder tbBody = new StringBuilder();
for (int i = 0; i < piList.Length; i++)
{
//Console.WriteLine(piList[i].GetMethod.Invoke(v, null));
object value = piList[i].GetMethod.Invoke(v, null);
tbBody.Append(value);//内容
tbBody.Append("\t");//自动跳到下一单元格
}
tbbody = tbBody.ToString();
tbbody = tbbody.Substring(0, tbbody.Length - 1) + "\n";//取完一行内容,换行
streamWriter.Write(tbbody);//内容写入
}
}
}
}
else
{
}
}
//学生数据生成
public class Student
{
private string id;
public string Id { get { return id; } set { id = value; } }
private string name;
public string Name { get { return name; } set { name = value; } }
private string age;
public string Age { get { return age; } set { age = value; } }
public List<Student> GetStudentData()
{
List<Student> studentList = new List<Student>();
Student s1 = new Student();
s1.Id = "1";
s1.Name = "haha";
s1.Age = "10";
Student s2 = new Student();
s2.Id = "2";
s2.Name = "xixi";
s2.Age = "20";
Student s3 = new Student();
s3.Id = "3";
s3.Name = "lolo";
s3.Age = "30";
studentList.Add(s1);
studentList.Add(s2);
studentList.Add(s3);
return studentList;
}
}