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


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

    简单的代码如下

    复制代码
     1         //mvc项目可以传多个id以逗号相隔的字符串
     2         public ActionResult execl(string ids)
     3         {
     4             List<PayLog> list = new List<PayLog>();//准备需要灌入excel的数据,paylog可替换你自己的数据类,这里因为是源代码所以没改
     5             string[] idsstring = ids.Split(new char[] { ',' }, StringSplitOptions.RemoveEmptyEntries);//拆字符串
     6             for (int j = 0; j < idsstring.Length; j++)//查找需要灌入的数据放入list里,asp.net这里为从dal层拿到的数据同样放入list
     7             {
     8                 string str = idsstring[j];
     9                 list.Add(DbSession.PayLogRepository.Fetch(x => x.FInvoiceId == str));//该写法为mvc写法,链接数据库读取数据对象
    10             }
    11             HSSFWorkbook work = new HSSFWorkbook();//创建excel文件对象
    12             HSSFSheet sheet = work.CreateSheet();//创建excel里的页,括号中可以写你想要该页的名字,默认sheet
    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";//项目中应该改为相对路径而不是绝对路径 //因不知道用户的excel版本所以生成文件后缀为.xls,因为2003版的excel后缀名为.xls,2007版后均为.xlsx
    24             using (FileStream file = new FileStream(path, FileMode.Create))//创建文件流,将灌好数据的excel文件写入服务器的硬盘
    25             {
    26                 work.Write(file);
    27             }
    28             return File(new FileStream(path, FileMode.Open), "application/ms-excel", "信息.xls");//提示用户下载服务器上的文件
    复制代码

    结果如图

     
     
     
    好文要顶 关注我 收藏该文  
  • 相关阅读:
    黑洞数
    三态门最简单的描述方法
    数据选择器的符号和真值表
    RGB的同步信号
    奇场和偶场在信号格式上的差别
    CPOL与CPHA
    Pixel Replication
    HDMI传输中MCLK的获得
    Protel99 1:1打印PCB
    二极管和整流管
  • 原文地址:https://www.cnblogs.com/soundcode/p/6268712.html
Copyright © 2020-2023  润新知