1、添加NPOI包,添加引用。
2、前端调用方法
<button type="button" class="btn btn-primary" onclick="ExportToExcel()">导出Excel</button>
<script type="text/javascript">
//导出Excel
function ExportToExcel() {
window.location.href = "/Home/DataExport"
}
</script>
3、后端写法
#region Excel导出 public FileResult DataExport() { List<Phone> ExListInfo = new List<Phone>(); Phone p = new Phone("小米5", "小米", "3500"); Phone p1 = new Phone("小米2A", "小米", "2500"); Phone p2 = new Phone("荣耀20Pro", "华为", "3500"); ExListInfo.Add(p); ExListInfo.Add(p1); ExListInfo.Add(p2); //ExportExcel(ExListInfo); //创建Excel文件的对象 NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); //添加一个sheet ISheet sheet1 = book.CreateSheet("Sheet1"); //貌似这里可以设置各种样式字体颜色背景等,但是不是很方便,这里就不设置了 //给sheet1添加第一行的头部标题 IRow row1 = sheet1.CreateRow(0); row1.CreateCell(0).SetCellValue("手机名称"); row1.CreateCell(1).SetCellValue("手机型号"); row1.CreateCell(2).SetCellValue("手机价格"); //....N行 //将数据逐步写入sheet1各个行 for (int i = 0; i < ExListInfo.Count; i++) { IRow rowtemp = sheet1.CreateRow(i + 1); rowtemp.CreateCell(0).SetCellValue(ExListInfo[i].PhoneName); rowtemp.CreateCell(1).SetCellValue(ExListInfo[i].PhoneType); rowtemp.CreateCell(2).SetCellValue(ExListInfo[i].PhonePrice); //....N行 } // 写入到客户端 MemoryStream ms = new MemoryStream(); book.Write(ms); ms.Seek(0, SeekOrigin.Begin); DateTime dt = DateTime.Now; string dateTime = dt.ToString("yyMMddHHmmssfff"); string fileName = "手清价格一览表" + dateTime + ".xls"; return File(ms, "application/vnd.ms-excel", fileName); } #endregion
4、效果展示
参考网址:
https://www.cnblogs.com/CallmeYhz/p/4997691.html