Lucky_dog

NPOI对Excel的读取

电脑版发表于:2020/1/13 16:03
public ActionResult Index()
        {
            //打开excel所在的位置
            FileStream stream = new FileStream(Server.MapPath("~/Content/excel/S3抽奖名单.xlsx"), FileMode.Open);
            //获取excel
            XSSFWorkbook workbook = new XSSFWorkbook(stream);
            //获取excel中的表
            XSSFSheet sheet = workbook.GetSheet("PHP46") as XSSFSheet;
            LotteryDBEntities lotteryDB = new LotteryDBEntities();

            //遍历行
            List<stuInfo> stulist = new List<stuInfo>();
            for (int i = 4; i < sheet.LastRowNum; i++)
            {
                XSSFRow row = sheet.GetRow(i) as XSSFRow;
                var name = row.GetCell(3);
                if (name == null)
                {
                    break;
                }
                string stuName = name.ToString();
                string clas = row.GetCell(8).StringCellValue;
                stuInfo stu = new stuInfo();
                stu.stuName = stuName;
                stu.stuClass = clas;
                stulist.Add(stu);
            }
            var info = lotteryDB.stuInfo.ToList();
            //批量添加
            lotteryDB.BulkInsert(stulist);
            lotteryDB.BulkSaveChanges();
            return View();
        }

拓展:

        这里读取数据之后向数据库批量添加数据时,使用了BulkInsert,这是一个拓展方法,添加数据时比EF自带的方法速度快一点,使用时,搜索 Z.EntityFramework.Extensions


关于TNBLOG
TNBLOG,技术分享。技术交流:群号677373950
ICP备案 :渝ICP备18016597号-1
App store Android
精彩评论
{{item.replyName}}
{{item.content}}
{{item.time}}
{{subpj.replyName}}
@{{subpj.beReplyName}}{{subpj.content}}
{{subpj.time}}
猜你喜欢