C#MVC DataTable数据导出到Execl

该博客内容展示了如何使用NPOI库导出Excel文件,包括设置标题、填充数据和返回给客户端。方法接收参数如年份、分析数据字段、学校类型和学校名,根据这些参数构建查询并生成Excel表格,最后将数据写入内存流并以文件形式返回给用户。
/// <summary>
        /// 导出Execl文件
        /// </summary>
        /// <returns></returns>
        public ActionResult WholeExportList(int Year, List<string> AnalyseDataField, string SchoolType, string SchoolName)
        {
        ///自定义返回类
            RongboRequest<AnalyseDataQuery> query = new RongboRequest<AnalyseDataQuery>();
            if (query.Data == null)
            {
                query.Data = new AnalyseDataQuery();
            }

            //获取基础参数
            //query.Data.AnalyseDataField = AnalyseDataField;
            query.Data.SchoolType = SchoolType;
            query.Data.SchoolName = SchoolName;

            query.Data.DistrictCode = this.DistrictCode;
            query.Data.Year = Year;

            //创建导出对象
            NPOI.HSSF.UserModel.HSSFWorkbook execl = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //添加一个sheet
            NPOI.SS.UserModel.ISheet sheet = execl.CreateSheet("Sheet1");
            //添加标题行
            NPOI.SS.UserModel.IRow head = sheet.CreateRow(0);
           
            //将标题写入execl
            head.CreateCell(0).SetCellValue("学校ID");
            head.CreateCell(1).SetCellValue("学校名称");
            int i = 1;
            var DataField = JsonConvert.SerializeObject(AnalyseDataField).Replace("]", "").Replace("[", "").Replace('"', '    ').Replace(" ", "").Split(",");

            List<string> ListData = new List<string>(); 
            foreach (var item in DataField)
            {
                i++;
                query.Data.AnalyseDataField = int.Parse(item);
              
                var analyseMB = _MB_ANALYSE_Bll.GetSingle(query.Data.AnalyseDataField).Data;
                ListData.Add(analyseMB.FieldName);
                if (analyseMB != null && !string.IsNullOrWhiteSpace(analyseMB.TableName)
                    && !string.IsNullOrWhiteSpace(analyseMB.FieldName)
                    )
                { 
                    //循环写入前端传入的标题
                    head.CreateCell(i).SetCellValue(analyseMB.FieldDescription);
                    //获取导出数据
                }
                else
                {
                   
                }
               
            }
            query.Data.ListData = ListData;
            ///DataTable 数据,我这里列不是固定列,所以要加控制
            DataTable page = _analyseDataBll.WholeExport(query);
            ///index 行索引,因为列头占用一行,所以从1开始
            /// create  导出的动态列不固定,所以加限制。
           /// ListData  前端传入的需要导出的列个数,因为前两列已经是固定的东西,所以create固定=2,循环完后重置
            int index = 1,create=2;
            foreach (DataRow item in page.Rows)
            {
                
                NPOI.SS.UserModel.IRow row = sheet.CreateRow(index);
                row.CreateCell(0).SetCellValue(item["XX_ID"].ToString());
                row.CreateCell(1).SetCellValue(item["XXMC"].ToString());
                foreach (var im in ListData)
                {
                    
                    row.CreateCell(create).SetCellValue(item[$"{im}"].ToString());
                    create++;
                }
                create = 2;
                index++;
                

            }
       
            // 写入到客户端 
            System.IO.MemoryStream stream = new System.IO.MemoryStream();
            execl.Write(stream);
            stream.Seek(0, SeekOrigin.Begin);
            string fileName = DateTime.Now.ToString("yyyy-MM-dd") + "数据采集导出信息.xls";
            return File(stream, "application/vnd.ms-excel", fileName);
            //return Json("");
        }
   
/// <summary> /// 导出Excel /// </summary> /// <param name="table"></param> /// <returns></returns> public bool ToExcel(DataTable table) { FileStream fs = new FileStream(this._filePath, FileMode.OpenOrCreate, FileAccess.ReadWrite); IWorkbook workBook = new HSSFWorkbook(); this._sheetName = this._sheetName.IsEmpty() ? "sheet1" : this._sheetName; ISheet sheet = workBook.CreateSheet(this._sheetName); //处理表格标题 IRow row = sheet.CreateRow(0); row.CreateCell(0).SetCellValue(this._title); sheet.AddMergedRegion(new CellRangeAddress(0, 0, 0, table.Columns.Count - 1)); row.Height = 500; ICellStyle cellStyle = workBook.CreateCellStyle(); IFont font = workBook.CreateFont(); font.FontName = "微软雅黑"; font.FontHeightInPoints = 17; cellStyle.SetFont(font); cellStyle.VerticalAlignment = VerticalAlignment.Center; cellStyle.Alignment = HorizontalAlignment.Center; row.Cells[0].CellStyle = cellStyle; //处理表格列头 row = sheet.CreateRow(1); for (int i = 0; i < table.Columns.Count; i++) { row.CreateCell(i).SetCellValue(table.Columns[i].ColumnName); row.Height = 350; sheet.AutoSizeColumn(i); } //处理数据内容 for (int i = 0; i < table.Rows.Count; i++) { row = sheet.CreateRow(2 + i); row.Height = 250; for (int j = 0; j < table.Columns.Count; j++) { row.CreateCell(j).SetCellValue(table.Rows[i][j].ToString()); sheet.SetColumnWidth(j, 256 * 15); } } //写入数据流 workBook.Write(fs); fs.Flush(); fs.Close(); return true; } /// <summary> /// 导出Excel /// </summary> /// <param name="table"></param> /// <param name="title"></param> /// <param name="sheetName"></param> /// <returns></returns> public bool ToExcel(DataTable table, string title, string sheetName, string filePath) { this._title = title; this._sheetName = sheetName; this._filePath = filePath; return ToExcel(table); }
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值