一区二区三区日韩精品-日韩经典一区二区三区-五月激情综合丁香婷婷-欧美精品中文字幕专区

分享

C# MVC 實(shí)現(xiàn)導(dǎo)入導(dǎo)出

 印度阿三17 2019-11-07

導(dǎo)入導(dǎo)出引用NPOI

?

?視圖

 1   <input type="button" name="name" class="btn btn-success btn-sm" onclick="GetExcel()" value="導(dǎo)出"  />
 2             <form action="/Default/Import" method="post" enctype="multipart/form-data">
 3                 <input type="file" name="file" id="file" />
 4                 <input type="submit" name="name" class="btn btn-success btn-sm" value="導(dǎo)入" />
 5             </form>
 6 <script>
 7     //導(dǎo)出
 8       function GetExcel() {
 9     //window.location.href刷新當(dāng)前頁面,當(dāng)前頁面打開URL頁面,同步提交
10     window.location.href = "@Url.Action("ExportByNPOI")";
11         }
12 </script>
Index.cshtml

控制器

using System;
using System.Collections.Generic;
using System.Data;
using System.Data.OleDb;
using System.IO;
using System.Linq;
using System.Threading.Tasks;
using System.Web;
using System.Web.Mvc;
using 導(dǎo)入導(dǎo)出.Models;

namespace 導(dǎo)入導(dǎo)出.Controllers
{
    public class DefaultController : Controller
    {
        /// <summary>
        /// 數(shù)據(jù)存儲(chǔ)
        /// </summary>
        //List<StudentViewModel> stu = new List<StudentViewModel>()
        //{
        //     new StudentViewModel{Id=1,Name="小明",Sex="男",DateTime="2019-11-07",Static=1},
        //     new StudentViewModel{Id=2,Name="小紅",Sex="女",DateTime="2019-11-08",Static=0},
        //     new StudentViewModel{Id=3,Name="小蘭",Sex="女",DateTime="2019-11-09",Static=0},
        //     new StudentViewModel{Id=4,Name="小天",Sex="男",DateTime="2019-11-11",Static=1},
        //     new StudentViewModel{Id=5,Name="阿亮",Sex="男",DateTime="2019-11-12",Static=0},
        //     new StudentViewModel{Id=6,Name="王大力",Sex="男",DateTime="2019-11-13",Static=1}
        //};
        string sql = "select * from student";
       
        // GET: Default
        public ActionResult Index()
        {
            List<StudentViewModel> stu = MySqlDBHelper.GetList<StudentViewModel>(sql);
            return View(stu);
        }
        /// <summary>
        /// 導(dǎo)出Excel
        /// </summary>
        /// <returns></returns>
        public ActionResult ExportByNPOI()
        {
            List<StudentViewModel> stu = MySqlDBHelper.GetList<StudentViewModel>(sql);
            //1、獲取數(shù)據(jù)源
            var result = stu;
            var list = result.Select(x => new { x.Id, x.Name, x.Sex, x.DateTime, x.Static }).ToList();
            //2、創(chuàng)建Excel文件的對(duì)象
            NPOI.HSSF.UserModel.HSSFWorkbook excel = new NPOI.HSSF.UserModel.HSSFWorkbook();
            //3、添加一個(gè)sheet
            NPOI.SS.UserModel.ISheet sheet = excel.CreateSheet("Sheet1");
            //給sheet1添加標(biāo)題行
            NPOI.SS.UserModel.IRow head = sheet.CreateRow(0);
            head.CreateCell(0).SetCellValue("編號(hào)");
            head.CreateCell(1).SetCellValue("姓名");
            head.CreateCell(2).SetCellValue("性別");
            head.CreateCell(3).SetCellValue("入學(xué)時(shí)間");
            head.CreateCell(4).SetCellValue("狀態(tài)");
            //將數(shù)據(jù)逐步寫入sheet1各個(gè)行
            for (int i = 0; i < list.Count; i  )
            {
                NPOI.SS.UserModel.IRow row = sheet.CreateRow(i   1);
                row.CreateCell(0).SetCellValue(list[i].Id);
                row.CreateCell(1).SetCellValue(list[i].Name);
                row.CreateCell(2).SetCellValue(list[i].Sex);
                row.CreateCell(3).SetCellValue(list[i].DateTime);
                row.CreateCell(4).SetCellValue(list[i].Static);
            }
            //寫入到客戶端
            System.IO.MemoryStream ms = new System.IO.MemoryStream();
            excel.Write(ms);
            ms.Seek(0, System.IO.SeekOrigin.Begin);
            return File(ms, "application/vnd.ms-excel", "顧客信息表.xls");
        }
        /// Excel導(dǎo)入
        /// </summary>
        /// <param name="filePath"></param>
        /// <returns></returns>
        public ActionResult Import(HttpPostedFileBase file)
        {
            
            string msg="";
            if (file == null)
            {
                msg = "導(dǎo)入失敗";
            }
            else
            {
                //1、先保存上傳的excel文件(這一步與上傳圖片流程一致)
                string extName = file.FileName;
                string path = Server.MapPath("~/Content/Files");
                string filename = Path.Combine(path, extName);
                file.SaveAs(filename);
                //2、讀取excel文件(通過oledb將excel數(shù)據(jù)填充到datatable)
                //HDR=Yes,這代表第一行是標(biāo)題,不做為數(shù)據(jù)使用,IMEX的含義(0:寫入,1:讀取,2:讀取與寫入)
                string filePath = filename;//必須是物理路徑
                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);
                //默認(rèn)讀取的Sheet1,你也可以把它封裝變量,動(dòng)態(tài)讀取你的Sheet工作表
                DataTable dt = new DataTable();
                adp.Fill(dt);
                //3、將table轉(zhuǎn)化成list
                List<StudentViewModel> list = new List<StudentViewModel>();

                if (dt.Rows.Count > 0)
                {
                    foreach (DataRow item in dt.Rows)
                    {
                        list.Add(new StudentViewModel()
                        {
                            //有哪個(gè)寫哪個(gè)
                            Id = int.Parse(item["編號(hào)"].ToString()),
                            Name = item["姓名"].ToString(),
                            Sex = item["性別"].ToString(),
                            DateTime = item["入學(xué)時(shí)間"].ToString(),
                            Static = int.Parse(item["狀態(tài)"].ToString())
                        });
                    }
                }
                //4、跨action傳值用tempdata
                //TempData["list"] = list;
                //return RedirectToAction("List");

                //如果不直接導(dǎo)入數(shù)據(jù)庫這里不用寫
                StudentViewModel model = new StudentViewModel();
                for (int i = 0; i < list.Count; i  )
                {
                    model.Id = list[i].Id;
                    model.Name = list[i].Name;
                    model.Sex = list[i].Sex;
                    model.DateTime = list[i].DateTime;
                    model.Static = list[i].Static;
                    //調(diào)用添加方法
                    //var result = await baseRepository.Add(model);
                    //if (result > 0)
                    //{
                    //  msg = "導(dǎo)入成功";
                    //}
                    DAL dal = new DAL();
                    int result = dal.Create(model);
                    if (result > 0)
                    {

                        msg = "導(dǎo)入成功!";
                    }
                }
            }
           
            return Json(msg);
        }
        public class DAL {
            public int Create(StudentViewModel model)
            {
                string sql = string.Format("insert into Student(Id,Name,Sex,DateTime,Static) values('{0}','{1}','{2}','{3}','{4}')", model.Id, model.Name, model.Sex, model.DateTime, model.Static);
                int result = MySqlDBHelper.ExecuteNonQuery(sql);
                return result;
            }
        }
    }
}
Controller

?

?

來源:https://www./content-1-550351.html

    本站是提供個(gè)人知識(shí)管理的網(wǎng)絡(luò)存儲(chǔ)空間,所有內(nèi)容均由用戶發(fā)布,不代表本站觀點(diǎn)。請(qǐng)注意甄別內(nèi)容中的聯(lián)系方式、誘導(dǎo)購買等信息,謹(jǐn)防詐騙。如發(fā)現(xiàn)有害或侵權(quán)內(nèi)容,請(qǐng)點(diǎn)擊一鍵舉報(bào)。
    轉(zhuǎn)藏 分享 獻(xiàn)花(0

    0條評(píng)論

    發(fā)表

    請(qǐng)遵守用戶 評(píng)論公約

    類似文章 更多

    91免费精品国自产拍偷拍| 人妻少妇av中文字幕乱码高清| 久热青青草视频在线观看| 国产av一二三区在线观看| 精品人妻一区二区三区四区久久| 日本加勒比在线观看一区| 成人国产一区二区三区精品麻豆| 太香蕉久久国产精品视频| 国产成人免费激情视频| 国产黑人一区二区三区| 日韩国产亚洲欧美激情| 久草视频在线视频在线观看| 国产成人精品一区二三区在线观看| 日韩欧美一区二区久久婷婷 | 亚洲一区二区三区在线免费| 草草夜色精品国产噜噜竹菊| 久久亚洲精品成人国产| 亚洲男人的天堂久久a| 欧美视频在线观看一区| 黄色片国产一区二区三区| 日韩欧美一区二区不卡视频| 欧美老太太性生活大片| 日韩精品视频香蕉视频| 很黄很污在线免费观看| 亚洲av成人一区二区三区在线| 欧美日韩校园春色激情偷拍| 欧美日韩成人在线一区| 日本人妻丰满熟妇久久| 激情图日韩精品中文字幕| 日本人妻熟女一区二区三区 | 精品国产亚洲av成人一区| 欧美日本道一区二区三区| 日本欧美视频在线观看免费| 国产成人一区二区三区久久| 欧美人妻少妇精品久久性色| 黄色国产一区二区三区| 91精品国产av一区二区| 日韩1区二区三区麻豆| 久久黄片免费播放大全| 夫妻性生活动态图视频| 99日韩在线视频精品免费|