C#下载Excel文件并且填充数据
电脑版发表于:2019/11/29 14:40
引用NPOI.dll文件库
using NPOI.HSSF.Model; using NPOI.HSSF.UserModel; using NPOI.HSSF.Util;
在当期项目添加一个Excel模板文件
下载操作(一个无返回值的方法)
public void DownExcel() { string url = Server.MapPath("~/Excel/temp.xls"); //读取文件 FileStream fileStream = new FileStream(url, FileMode.Open); //读工作表 HSSFWorkbook work = new HSSFWorkbook(fileStream); //读取表 //得到工作表 HSSFSheet hSSFSheet = work.GetSheet("Sheet1") as HSSFSheet; //循环添加数据--具体有数据库来 for (int i = 2; i <=10; i++) { HSSFRow hSSFRow = hSSFSheet.CreateRow(i) as HSSFRow; for (int j = 0; j <= 2; j++) { hSSFRow.CreateCell(j).SetCellValue("姓名" + i+"号"); } } //下载操作必备操作 MemoryStream memoryStream = new MemoryStream(); work.Write(memoryStream); Response.AddHeader("Content-Disposition", "attachment; filename=临时表.xls"); Response.BinaryWrite(memoryStream.ToArray()); }