///
///
数据
///
表名
///
true,覆盖单元格,false追加内容(list和创建的excel或excel模板)
///
true-xlsx,false-xls
///
返回文件
public static MemoryStream ParseListToExcel
(List list, string sheetName = "sheet1", bool overwrite = true, bool xlsx = true) where T : class
var mapper = new Mapper();
MemoryStream ms = new MemoryStream();
mapper.Save(ms, list, sheetName, overwrite, xlsx);
return ms;
///
/// Excel转为List
///
///
///
///
///
public static List ParseExcelToList(Stream fileStream, string sheetname = "") where T : class
List ModelList = new List();
var mapper = new Mapper(fileStream);
List> DataList = new List>();
if (!string.IsNullOrEmpty(sheetname))
DataList = mapper.Take(sheetname).ToList();
DataList = mapper.Take().ToList();
if (DataList != null && DataList.Count > 0)
foreach (var item in DataList)
ModelList.Add(item.Value);
return ModelList;
增加一个User Model用作导出,Column指明导出时表头显示的列名
public class User
[Column("用户ID")]
public int UserId { get; set; }
[Column("用户名")]
public string UserName { get; set; }
[Column("手机号")]
public string Phone { get; set; }
[Column("邮箱")]
public string Email { get; set; }
增加一个FileController控制器
public class FileController : Controller
public IActionResult Index()
return View();
[HttpPost]
public IActionResult Upload()
//用户List
List<User> users = new List<User>();
//获取到上传的文件
var file = Request.Form.Files[0];
//文件转成流
using (var fileStream = file.OpenReadStream())
//excel转实体
users = ExcelHelper.ParseExcelToList<User>(fileStream, "Sheet1");
return Content(JsonConvert.SerializeObject(users));
public IActionResult DownLoad()
//生成List
List<User> usrs = new List<User>();
for(int i=1;i<=10;i++)
User user = new User()
UserId = i,
UserName = "用户" + i,
Phone = "13800000000",
Email = $"user{i}@qq.com"
usrs.Add(user);
//List转为Excel文件
var fileStream = ExcelHelper.ParseListToExcel(usrs);
return File(fileStream.ToArray(), "application/vnd.ms-excel", "用户信息.xlsx");
Index的视图
<a href="/File/DownLoad">导出excel文件</a>
<form action="/File/Upload" method="post" enctype="multipart/form-data" >
选择excel文件: <input type="file" name="file" />
<input type="submit" value="上传excel" />
</form>
运行后界面