MVC 導入excel

    /// <summary>
        /// 導入excel
        /// </summary>
        /// <returns></returns>
        public ActionResult Import()
        {
            HttpPostedFileBase file = Request.Files["excel"];
            //1、先保存上傳的excel文件(這一步與上傳圖片流程一致)
            string extName = Path.GetExtension(file.FileName).ToLower();
            string newFileName = System.Guid.NewGuid().ToString();
            string path = Server.MapPath("~/Files/");
            file.SaveAs(path + newFileName + extName);
            //2、讀取excel文件(通過oledb將excel數據填充到datatable)
            //HDR=Yes,這代表第一行是標題,不做爲數據使用,IMEX的含義(0:寫入,1:讀取,2:讀取與寫入)
            string filePath = path + newFileName + extName;//必須是物理路徑
            string conStr = "Provider=Microsoft.ACE.OLEDB.12.0; Persist Security Info=False;Data Source=" + filePath + "; Extended Properties='Excel 8.0;HDR=Yes;IMEX=1'";
           
            OleDbDataAdapter adp = new OleDbDataAdapter("select * From[Sheet1$]", conStr); //默認讀取的Sheet1,你也可以把它封裝變量,動態讀取你的Sheet工作表
            
            DataTable dt = new DataTable();
            adp.Fill(dt);
            //3、將table轉化成list
            List<Person> list = new List<Person>();
            if (dt.Rows.Count > 0)
            {
                foreach (DataRow item in dt.Rows)
                {
                    list.Add(new Person() {

                        ID = Convert.ToInt32(item["編號"]),
                        Name = item["姓名"].ToString(),
                        Age = Convert.ToInt32(item["年齡"]),
                        Sex = item["性別"].ToString()
                    
                    });
                }
            }

           //4、跨action傳值用tempdata

            //TempData["list"] = list;
            //return RedirectToAction("List");

            //5、指向新的view
            return View("List", list);
        }
/// <summary>
        /// 通過第三方插件npoi導入excel
        /// </summary>
        /// <returns></returns>
        public ActionResult ImportByNPOI()
        {
            HttpPostedFileBase file = Request.Files["excel"];
            ////1、獲取上傳的圖片(不用保存)
            //string extName = Path.GetExtension(file.FileName).ToLower();
            //string newFileName = System.Guid.NewGuid().ToString();
            //string path = Server.MapPath("~/Files/");
            //file.SaveAs(path + newFileName + extName);
            //2、將上傳文件轉化成excel對象
            NPOI.HSSF.UserModel.HSSFWorkbook excel = new NPOI.HSSF.UserModel.HSSFWorkbook(file.InputStream);
            NPOI.HSSF.UserModel.HSSFSheet sheet = excel.GetSheetAt(0) as NPOI.HSSF.UserModel.HSSFSheet;
            int rowNum = sheet.PhysicalNumberOfRows;//獲取行數
            List<Person> list = new List<Person>();
            for (int i = 1; i < rowNum; i++)//從第2行開始
            {
                NPOI.HSSF.UserModel.HSSFRow row = sheet.GetRow(i) as NPOI.HSSF.UserModel.HSSFRow;
                list.Add(new Person()
                {


                    ID = Convert.ToInt32(row.GetCell(0).ToString()),
                    Name = row.GetCell(1).ToString(),
                    Age = Convert.ToInt32(row.GetCell(2).ToString()),
                    Sex = row.GetCell(3).ToString()


                });
            }
            return View("List", list);


        }

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章