public FileResult ExcelFile()
{
//new 一个列表待用
List<Student> allList = new List<Student>();
//将该表中所有数据获取出来
var slist = bll.GetAllList();
Student model = new Student();
//判断是否存在记录
if(slist!=null&&slist.Count()!=0)
{
//若存在记录就将每一条记录传至实体的对象中,然后添加进allList列表里
foreach(var item in slist)
{
model.StudentName = item.StudentName ;
model.Sex = item.Sex;
model.Birthday = item.Birthday;
allList.Add(model);
}
}
//创建一个Excel工作簿
HSSFWorkbook book = new HSSFWorkbook();
//在工作簿中创建一个名为Sheet1的Excel表
ISheet sheet = book.CreateSheet("Sheet1");
//在该sheet中new一个第一行的对象,并填充3列数据
IRow row = sheet.CreateRow(0);
row.CreateCell(0).SetCellValue("姓名");
row.CreateCell(1).SetCellValue("性别");
row.CreateCell(2).SetCellValue("出生日期");
//获取allList列表中的所有数据添加到该sheet中
for(int i=0;i<allList.Count;i++)
{
IRow rowtemp = sheet.CreateRow(i+1);
rowtem.CreateCell(0).SetCellValue(allList[i].StudentName.ToString());
rowtemp.CreateCell(2).SetCellValue(allList[i].Sex.ToString()=="0"?"男":"女");
rowtemp.CreateCell(3).SetCellValue(allList[i].Birthday.ToString());
}
//创建一个内存流
MemoryStream ms = new MemoryStream();
//保存到默认路径中
book.Write(ms);
//设置当前流的位置
ms.Seek(0,SeekOrigin.Begin);
DateTime dt = DateTime.Now;
//确定文件名
string dateTime = dt.ToString("yyyyMMddHHmmss");
string fileName = "结果"+dateTime+".xls";
return File(ms,"application/vnd.ms-excel",fileName);
}