首先我们要先引用以下的dll
链接:https://pan.baidu.com/s/1oWhWYIJvaJ7-15IzTzlTrA
提取码:xz29
复制这段内容后打开百度网盘手机App,操作更方便哦
using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using 导入导出.ef;
using NPOI;
using NPOI.SS.UserModel;
using NPOI.XSSF.UserModel;
using NPOI.HSSF.UserModel;
using System.IO;
namespace 导入导出.Controllers
{
public class StudentController : Controller
{
// GET: Student
public ActionResult Index()
{
StudentDal n = new StudentDal();
return View(n.GetStudents());
}
//当点击导出按钮时 ajax跳到Dao
public string Dao()
{
StudentDal n = new StudentDal();
List<Student> list = n.GetStudents();
HSSFWorkbook workbook = new HSSFWorkbook();
ISheet sheet = workbook.CreateSheet("学生信息表");
IRow row = sheet.CreateRow(0);
row.CreateCell(0).SetCellValue("姓名");
row.CreateCell(1).SetCellValue("性别");
row.CreateCell(2).SetCellValue("手机号");
row.CreateCell(3).SetCellValue("地址");
for (int i = 0; i <list.Count ; i++)
{
IRow cells = sheet.CreateRow(i+1);
//为指定行添加列
cells.CreateCell(0).SetCellValue(list[i].Name);
cells.CreateCell(1).SetCellValue(list[i].Sex);
cells.CreateCell(2).SetCellValue(list[i].Phone);
cells.CreateCell(3).SetCellValue(list[i].Aid.ToString());
}
//使用文件流做数据的写入
using (FileStream fss=new FileStream(@"C: \Users\15980\Desktop\到\学生信息表.xls",FileMode.Create))
{
workbook.Write(fss);
}
return "导出成功";
}
//ef
class StudentDal
{
Model1 N = new Model1();
//显示数据
public List<Student> GetStudents()
{
return N.Student.ToList();
}
}
}
}