数据用记事本打开导入数据库

数据里面包含了含姓名、出生日期和住址、手机号等个人信息!

把这些文件保存为记事本格式,读取数据添加到数据库

建立数据库模型类HotelDataModels

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.ComponentModel.DataAnnotations.Schema;
using System.Data.Entity;
using System.Globalization;
using System.Web.Mvc;
using System.Web.Security;

namespace MvcHotelData.Models
{
    public class HotelDataModels
    {
        [Key]
        public int ID { get; set; }

        [Required]
        [Display(Name = "姓名")]
        public string Name { get; set; }

        [Display(Name = "身份证号")]
        public string ctfId { get; set; }

        [Display(Name = "性别")]
        public string Gender { get; set; }

        [Display(Name = "出生日期")]
        public DateTime Birthday { get; set; }

        [Display(Name = "地址")]
        public string Address { get; set; }

        [Display(Name = "手机号")]
        public string Tel { get; set; }

        [Display(Name = "记录日期")]
        public DateTime Version { get; set; }
    }

    public class HotelDataDBContext : DbContext
    {
        public DbSet<HotelDataModels> HotelDataModels { get; set; }
    }
}

 导入到数据库

        public ActionResult Import()
        {
            //1.读取文件
            using (StreamReader reader = new StreamReader(@"C:Users00000000000DesktopMvcHotelDataMvcHotelDataContent123.txt", Encoding.Default))
            {
                //循环读取每一行
                string line = null;
                while ((line = reader.ReadLine()) != null)
                {
                    string[] parts = line.Split(',');

                    if(parts.Length==33)
                    {   
                    HotelDataModels h = new HotelDataModels();
                    h.Name = parts[0];
                    h.ctfId = parts[4];
                    h.Gender = parts[5];

                    if (parts[6].Trim() != "" && parts[6].Trim().Length == 8 && Convert.ToInt32(parts[6].Trim())>19000101)
                    {
                        h.Birthday = DateTime.ParseExact(parts[6], "yyyyMMdd", null);
                    }
                    else { h.Birthday = DateTime.Parse("1900-01-01 00:00:00"); }
                 
                    h.Address = parts[7];
                    h.Tel = parts[19];
                    h.Version = DateTime.Parse(parts[31]);
                    db.HotelDataModels.Add(h);
                    db.SaveChanges();
                    }
                }
            }
            return Content("<script language='javascript' type='text/javascript'>alert('导入完毕!');history.go(-1);</script>");
        }
原文地址:https://www.cnblogs.com/yechangzhong-826217795/p/5129674.html