引入Aspose
百度网盘=>传送门,提取码为urn7,下载完后将压缩包里的两个dll文件引用到项目中
创建一个excel模版
我们只导入数据,所以要事先准备好一个excel的模版,如下图为我准备的模版

它存放在我的项目ExcelTemp文件夹中
导出excel代码
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 |
public ActionResult DcExcel() { //读取数据 var result = uBll.GetList(u => true).Select(u => new { u.Address, u.Email, u.Money, u.RealName, title = u.Dept.Title, u.ID }); //读取模板 Workbook book = new Workbook(); book.Open(Server.MapPath("/ExcelTemp/员工模板表.xlsx")); //获取sheet var sheet = book.Worksheets[0]; //获取单元格 var cell = sheet.Cells; int row = 2; //插入数据 foreach (var item in result) { cell[row, 0].PutValue(item.ID); cell[row, 1].PutValue(item.RealName); cell[row, 2].PutValue(item.title); cell[row, 3].PutValue(item.Email); cell[row, 4].PutValue(item.Money); cell[row, 5].PutValue(item.Address); row++; } //保存 string fileName = Guid.NewGuid().ToString() + ".xlsx"; book.Save(Server.MapPath("/TempExcel") + "\\" + fileName); //下载 return File(Server.MapPath("/TempExcel") + "\\" + fileName, "application/book", "员工表.xlsx"); } |
Worksheets[0]是excel表sheet 部分的位置

cell[row, 0].PutValue(item.ID);row为行,0为列,putvalue中是要循环添加到excel表中的数据。
添加数据完成后将导入完成的excel表保存在临时文件夹TempExcel中,return File(Server.MapPath("/TempExcel") + "\" + fileName, "application/book", "员工表.xlsx");让用户从临时文件夹中下载excel表,文件名为员工表,
application/book 是文件类型。
小插曲
临时文件夹的excel表只要点击导出就会生成一个,所以要写一个方法定期删除该文件夹中的数据。
效果图

点击导出之后就开始下载,此为下载好的excel表


评论