使用NPOI将数据库里信息导出Excel表格并提示用户下载

使用NPOI进行导出Excel表格大家基本都会,我在网上却很少找到导出Excel表格并提示下载的

简单的代码如下

 1         //mvc项目可以传多个id以逗号相隔的字符串

 2         public ActionResult execl(string ids)

 3         {

 4             List<PayLog> list = new List<PayLog>();

 5             string[] idsstring = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);//拆字符串

 6             for (int j = 0; j < idsstring.Length; j++)

 7             {

 8                 string str = idsstring[j];

 9                 list.Add(DbSession.PayLogRepository.Fetch(x => x.FInvoiceId == str));//链接数据库读取数据对象

10             }

11             HSSFWorkbook work = new HSSFWorkbook();//创建页

12             HSSFSheet sheet = work.CreateSheet();//创建列

13             HSSFRow row = sheet.CreateRow(0);//第一行

14             row.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue("流水号");

15             row.CreateCell(1, HSSFCell.CELL_TYPE_STRING).SetCellValue("编码");

16             //循环对象集合创建数据列

17             for (int i = 0; i < list.Count; i++)

18             {

19                 HSSFRow rows = sheet.CreateRow(i + 1);

20                 rows.CreateCell(0, HSSFCell.CELL_TYPE_STRING).SetCellValue(list[i].FPayInNo);

21                 rows.CreateCell(1, HSSFCell.CELL_TYPE_STRING).SetCellValue(list[i].FEnterpriseId);

22             }

23             string path = @"F:\信息.xls";//项目中应改为相对路径而不是绝对路径

24             using (FileStream file = new FileStream(path, FileMode.Create))

25             {

26                 work.Write(file);

27             }

28             return File(new FileStream(path, FileMode.Open), "application/ms-excel", "信息.xls");

结果如图

使用NPOI将数据库里信息导出Excel表格并提示用户下载

你可能感兴趣的:(导出Excel)