.net mvc NPOI模板导出数据到excel
小白浏览:6582020-08-27 17:39:50本文累计收益:0我也要赚钱
        /// <summary>
        /// 使用模板导出Excel
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="list">导出数据集</param>
        /// <param name="index">从模板中第几个输出数据</param>
        /// <param name="tempPath">模板存放路径</param>
        /// <param name="exportPath">导出文件存放路径</param>
        /// <returns></returns>
        public string TemplateOutput<T>(List<T> list, int index, string tempPath, string exportPath)
        {
            //创建目录
            if (!Directory.Exists(exportPath))
                Directory.CreateDirectory(exportPath);
            using (MemoryStream ms = new MemoryStream())
            {
                string extension = Path.GetExtension(tempPath);
                FileStream fs = System.IO.File.OpenRead(tempPath);
                IWorkbook workbook = null;
                if (extension.Equals(".xls"))
                {
                    workbook = new HSSFWorkbook(fs);//创建Excel工作簿
                }
                else
                {
                    workbook = new XSSFWorkbook(fs);
                }
                fs.Close();
                ISheet sheet = workbook.GetSheetAt(0);//创建工作表
                IRow rows = null;
                //循环数据写入excel
                for (int i = 0; i < list.Count; i++)
                {
                    //rows = sheet.CreateRow(i + index - 1);
                    rows = sheet.GetRow(i + index - 1);
                    int j = 0;
                    var Typed = typeof(T);
                    System.Reflection.PropertyInfo[] properties = list[i].GetType().GetProperties(System.Reflection.BindingFlags.Instance | System.Reflection.BindingFlags.Public);
                    foreach (System.Reflection.PropertyInfo item in properties)
                    {
                        string name = item.Name;
                        object value = item.GetValue(list[i], null);
                        if (item.PropertyType.IsValueType || item.PropertyType.Name.StartsWith("String"))
                        {
                            //rows.CreateCell(j).SetCellValue(value.ToString());
                            rows.GetCell(j).SetCellValue(value.ToString());
                            j++;
                        }
                        else
                        {
                            return "Error";
                        }
                    }
                }
                workbook.Write(ms);
                var buf = ms.ToArray();
                //保存为Excel文件
                string fileName = ClassesLib.GetIdByTime() + extension;
                string downLoadPath = exportPath + fileName;
                using (FileStream fsTmp = new FileStream(downLoadPath, FileMode.Create, FileAccess.Write))
                {
                    fsTmp.Write(buf, 0, buf.Length);
                    fsTmp.Flush();
                    fsTmp.Close();
                }
                return fileName;
            }
        }

//调用方法
            try
            {
                string sYear = Convert.ToDateTime(genDate + "-01").Year.ToString();
                string sMonth = Convert.ToDateTime(genDate + "-01").Month.ToString();
                string sqlStr = "SELECT ID,COUNTY,PLANCOUNT,FINISHCOUNT,FINISHRATE,TOPPLANCOUNT,TOPFINISHCOUNT,TOPFINISHRATE,BSCOUNT,SSCOUNT,BKCOUNT,DPLANTCOUNT,DPLANTBSCOUNT,DPLANTSSCOUNT,DPLANTBKCOUNT FROM COUNTY_KEY_INDUSTRY_TOTAL WHERE SYEAR='" + sYear + "' AND SMONTH='" + sMonth + "'";
                var list = db.Database.SqlQuery<KeyIndustryListView>(sqlStr).ToList();//获取总页数
                //模板路径
                string tempPath = System.Web.HttpContext.Current.Server.MapPath("~/Content/Template/exportTemp.xls");
                string exportPath = Server.MapPath("/UploadFiles/DownloadFile/");
                //保存路径
                string fileName = TemplateOutput(list,6, tempPath, exportPath);
                return Redirect("/UploadFiles/DownloadFile/" + fileName);
            }
            catch (Exception e) { return Content(e.Message); }

 

评论列表
发表评论
+ 关注