• MVC 实现表格数据导出Excel(NPOI方式)


    前端View(@ViewBag为查询条件):

    <span id="exprobtn" class="btn_blue" style="dispaly:block;float:left;margin-left:5px;"><a href='/RunSum/Excel?date_Start=@ViewBag.dateStart&date_End=@ViewBag.dateEnd' target='_blank' style="color:white">导出</a></span>

    后台Controller:

            //导出excel
            public FileResult Excel()
            {
                //获取list数据
                string date_Start = string.Empty;
                string date_End = string.Empty;
                string strlist = string.Empty;
    
                date_Start = Request["date_Start"] ?? "";
                date_End = Request["date_End"] ?? "";
    
    //调用WebService获取数据 DTWebService.WebService ws
    = new DTWebService.WebService(); try { strlist = ws.GetMJData(date_Start, date_End); } catch (Exception ex) { WriteLog(ex.ToString()); }
    //将WebService获取的数据反序列成 泛型List<T> List
    <Xdbmjcs> list = Newtonsoft.Json.JsonConvert.DeserializeObject<List<Xdbmjcs>>(strlist); //创建Excel文件的对象 NPOI.HSSF.UserModel.HSSFWorkbook book = new NPOI.HSSF.UserModel.HSSFWorkbook(); //添加一个sheet NPOI.SS.UserModel.ISheet sheet1 = book.CreateSheet("消毒包灭菌次数统计"); //给sheet1添加第一行的头部标题 NPOI.SS.UserModel.IRow row1 = sheet1.CreateRow(0); row1.CreateCell(0).SetCellValue("序号"); row1.CreateCell(1).SetCellValue("消毒包编码"); row1.CreateCell(2).SetCellValue("消毒包名称"); row1.CreateCell(3).SetCellValue("消毒次数"); row1.CreateCell(4).SetCellValue("每次消毒费用"); row1.CreateCell(5).SetCellValue("金额");

    //设置小数位
                IDataFormat dataformat = book.CreateDataFormat();
                ICellStyle style0 = book.CreateCellStyle();
                style0.DataFormat = dataformat.GetFormat("0.00");
    //将数据逐步写入sheet1各个行 for (int i = 0; i < list.Count; i++) { NPOI.SS.UserModel.IRow rowtemp = sheet1.CreateRow(i + 1); rowtemp.CreateCell(0).SetCellValue(list[i].FRowNo); rowtemp.CreateCell(1).SetCellValue(list[i].FXdbbm); rowtemp.CreateCell(2).SetCellValue(list[i].FXdbmc); rowtemp.CreateCell(3).SetCellValue(list[i].FXdcs); rowtemp.CreateCell(4).SetCellValue((double)list[i].FMcxdfy);
     rowtemp.GetCell(4).CellStyle = style0; rowtemp.CreateCell(
    5).SetCellValue((double)list[i].FMoney);
     rowtemp.GetCell(5).CellStyle = style0; }
    //列宽自适应,只对英文和数字有效 for (int i = 0; i <= list.Count; i++) { sheet1.AutoSizeColumn(i); } // 写入到客户端 System.IO.MemoryStream ms = new System.IO.MemoryStream(); book.Write(ms); ms.Seek(0, SeekOrigin.Begin);
    //根据浏览器设置是直接默认下载到指定路径还是询问选址
    return File(ms, "application/vnd.ms-excel", "消毒包灭菌次数统计.xls"); }
  • 相关阅读:
    VMware中Ubuntu 14.04出现Unknown Display问题解决
    VMWare桥接、NAT和only-host三种模式
    Tomcat目录下文件详解
    Java socket2
    Java socket1
    网络基础知识
    java awt 乱码问题
    窗口Dialog
    windowsEvents
    鼠标适配器Adapter
  • 原文地址:https://www.cnblogs.com/Violety/p/9447754.html
Copyright © 2020-2023  润新知