1. 程式人生 > >用Visual Studio(C#) 實現Excel資料匯入(對映)

用Visual Studio(C#) 實現Excel資料匯入(對映)

本方法缺點:資料量有一定的限制,若列資料過多,則只能匯入2000條左右。此方法必須對錶格中的列進行類宣告。

1.get:

 public virtual async Task<ActionResult> ImportStudentMessage(int page = 1)
        {
            return View(await db.StudentInforms.GetPagedDataAsyns(new PageDataParameter<StudentInform, Guid>(page: page)));
        }
``

2.檢視頁面

@using (Html.BeginForm("ImportStudentMessage", "StudentInforms", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
    <div form-group>
        <div class="row">
            <div class="clearfix">
                <div class="col-xs-4">
                    <div
class="pull-left"> <input name="file" type="file" class="form-control" accept=".xls,.xlsx" /> </div> <div class="pull-right"> <input type="submit" value="匯入" class="btn btn-success btn-sm" /> @Html.ValidationMessage("file"
, "", new { @class = "text-danger" }) </div> </div> </div> </div> </div> }

3.post方法

[HttpPost]
        //[Authorize]
        public virtual ActionResult ImportStudentMessage(string file, bool stopWhenError = false)
        {
            if (Request.Files.Count > 0)
            {
                if (Request.Files[0].ContentLength > 0)
                {
                    string contentType = Request.Files[0].ContentType;
                    Guid fileId = Guid.NewGuid();
                    string path = Server.MapPath("\\Uploads");
                    string fileNameWithoutPath = System.IO.Path.GetFileName(Request.Files[0].FileName);
                    string fileName = fileId.ToString().Replace("-", "") + fileNameWithoutPath;
                    fileName = System.IO.Path.Combine(path, fileName);
                    try
                    {
                        Request.Files[0].SaveAs(fileName);
                        int rows = ImportStudentsFile1(fileName, stopWhenError);
                    }
                    catch (Exception ex)
                    {
                        ModelState.AddModelError("", "匯入時發生錯誤,可能是檔案格式非法,請將檔案開啟後另存為Excel2007以上的格式或聯絡管理員");
                    }
                }
                else
                    ModelState.AddModelError("", "請選擇匯入檔案");
            }
            else {
                ModelState.AddModelError("", "請選擇匯入檔案");
            }
            //return View(db.StudentInforms.ToList());
            return RedirectToAction("Index");
        }

4.ImportStudentsFile1()方法

 private int ImportStudentsFile1(string fileName, bool stopWhenError = false)
        {
            string[] data = { "考生號", "姓名", "身份證號", "性別程式碼", "民族程式碼", "政治面貌程式碼", "院校程式碼", "分校名稱", "學歷程式碼", "專業程式碼", "專業方向", "培養方式程式碼", "定向或委培單位", "生源所在地", "城鄉生源", "學制", "入學時間", "畢業時間", "師範生類別程式碼", "困難生類別程式碼", "所在院系", "所在班級", "學號", "出生日期", "入學前檔案所在單位", "入學前戶口所在地派出所", "檔案是否轉入學校", "戶口是否轉入學校", "手機號碼", "電子郵箱", "QQ號碼", "家庭住址", "家庭電話", "家庭郵編", "畢業去向程式碼", "單位名稱", "單位性質程式碼", "單位行業程式碼", "單位所在地", "工作職位類別程式碼", "單位聯絡人", "聯絡人電話", "聯絡人手機", "聯絡人電子郵箱", "聯絡人傳真", "單位地址", "單位郵編", "報到證簽發類別程式碼", "報到證籤往單位名稱", "籤往單位所在地", "報到證編號", "報到起始時間", "檔案轉寄單位名稱", "檔案轉寄單位地址", "檔案轉寄單位郵編", "戶口遷轉地址","協議書號", "檔案所在地", "檔案郵寄地址" };
            string[] property = { "No", "Name", "IDNumber", "SexCode", "NationCode", "PoliticalStatusCode", "CollegeCode", "BranchCollege", "DegreeCode", "MajorCode", "MajorField", "CultivationModeCode", "DirectionalUnit", "BirthPlaceCode", "StudentsFromUrbanAndRural", "EducationalSystem", "TermBeginTime", "GraduateTime", "NormalSchoolStudentTypeCode", "PoorStudentTypeCode", "Academy", "Class", "StudentNo", "Birthday", "BeforeEnrolRecordUnit", "BeforeEnrolResidenceLocationPolice", "RecordIsIntoSchool", "ResidenceIsIntoSchool", "Phone", "Email", "QQNumber", "Address", "HomePhone", "HomePostcode", "GraduateWhereaboutsCode", "UnitName", "UnitPropertyCode", "UnitIndustryCode", "UnitPlaceCode", "JobPositionType", "UnitContacts", "ContactPhone", "ContactTelephone", "ContactEmail", "ContactFax", "UnitAddress", "UnitPostcode", "ReportCardIssueTypeCode", "ReportCardToIssueUnitName", "ToIssueUnitPlaceCode", "ReportCardNo", "ReportStartTime", "RecordRedirectUnitName", "RecordRedirectUnitAddress", "RecordRedirectUnitPostcode", "ResidenceMovePlace", "ProtocolId", "Archives", "Postaddress" };
            return Import(fileName, data, property);
        }

5.Import()方法

 private int Import(string fileName, string[] data, string[] property)
        {
            System.Data.OleDb.OleDbConnectionStringBuilder stringBuilder = new System.Data.OleDb.OleDbConnectionStringBuilder();
            stringBuilder.DataSource = fileName;
            stringBuilder.Provider = "Microsoft.ACE.OLEDB.12.0";
            stringBuilder.Add("Extended Properties", "Excel 12.0 Xml;HDR=YES");
            int rows = 0;
            using (System.Data.OleDb.OleDbConnection connection = new System.Data.OleDb.OleDbConnection(stringBuilder.ConnectionString))
            {
                connection.Open();
                DataTable table = connection.GetSchema("tables", new string[] { null, null, null, "TABLE" });
                if (table.Rows.Count == 0)
                    throw new Exception("未找到匯入資料");
                string tableName = table.Rows[0]["TABLE_NAME"].ToString();
                string sql = string.Format("SELECT * FROM [{0}]", tableName);
                System.Data.OleDb.OleDbCommand command = new System.Data.OleDb.OleDbCommand(sql, connection);
                using (var reader = command.ExecuteReader())
                {
                    int[] dadaFielIndex = new int[data.Length];

                    for (int i = 0; i < data.Length; i++)
                    {
                        dadaFielIndex[i] = reader.GetOrdinal(data[i]);
                    }
                    if (dadaFielIndex[1] < 0) throw new Exception("未找到“姓名”列");
                    if (dadaFielIndex[2] < 0) throw new Exception("未找到“身份證號”列");
                    while (reader.Read())
                    {
                        string[] dataInformation = new string[dadaFielIndex.Length];
                        for (int i = 0; i < dadaFielIndex.Length; i++)
                        {
                            dataInformation[i] = reader[dadaFielIndex[i]].ToString().Trim();
                        }
                        string idNumber = reader["身份證號"].ToString().Trim();
                        int count = db.StudentInforms.Where(s => s.IDNumber == idNumber).Count();
                        StudentInform studentInformation = null;
                        if (count > 0)
                        {
                            studentInformation = db.StudentInforms.Where(s => s.IDNumber == idNumber).FirstOrDefault();
                            //stopWhenError = true;
                            //if (stopWhenError)
                            //    throw new Exception(string.Format("身份證“{0}”已經存在", idNumber));
                            //else
                            //    continue;
                        }
                        if (studentInformation == null)
                            studentInformation = new StudentInform();
                        Type t = typeof(StudentInform);

                        //string names = String.Join("\",\"", t.GetProperties().Select(w => w.Name));
                        for (int i = 0; i < property.Length; i++)
                        {
                            PropertyInfo propertyInfo = t.GetProperty(property[i]);
                            if (propertyInfo.PropertyType == typeof(DateTime))
                            {
                                DateTime time;
                                if (dataInformation[i].Length == 8)
                                {
                                    time = DateTime.ParseExact(dataInformation[i], "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
                                }
                                else
                                if (dataInformation[i].Length == 6)
                                {
                                    time = DateTime.ParseExact(dataInformation[i] + "01", "yyyyMMdd", System.Globalization.CultureInfo.CurrentCulture);
                                }
                                else
                                {
                                    time = DateTime.Now;
                                }

                                propertyInfo.SetValue(studentInformation, time, null);
                            }
                            else if (propertyInfo.PropertyType == typeof(bool))
                            {
                                propertyInfo.SetValue(studentInformation, false, null);
                            }
                            //else if (i == 57)
                            //{
                            //    propertyInfo.SetValue(studentInformation, common.encryptPassWord(dataInformation[2].Substring(12, 6)), null);
                            //}
                            else
                                propertyInfo.SetValue(studentInformation, dataInformation[i], null);
                        }
                        //迴圈賦值 
                        //foreach (var item in t.GetProperties())
                        //{
                        //    item.SetValue(studentInformation, dataInformation[j], null);
                        //    j++;
                        //}
                        //單獨賦值 
                        if (count == 0)
                        {
                            t.GetProperty("Id").SetValue(studentInformation, Guid.NewGuid(), null);
                            studentInformation.Password = common.encryptPassWord(studentInformation.IDNumber.Substring(12, 6));
                            studentInformation.PasswordStatus = false;
                            db.StudentInforms.Add(studentInformation);
                        }
                        db.SaveChanges();
                        rows++;
                    }
                    reader.Close();
                }
                connection.Close();
            }
            return rows;
        }