Advertisement
hubert17

Excel Import Users Students

Jan 19th, 2018
340
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
C# 5.95 KB | None | 0 0
  1. using SimpleExcelImport;
  2. using System;
  3. using System.Collections.Generic;
  4. using System.Linq;
  5. using System.Web;
  6. using System.Web.Mvc;
  7. using System.IO;
  8. using MyAspNetMvcApp.Areas.Examples.ViewModels;
  9. using MyAspNetMvcApp.Areas.Examples.Models;
  10. using System.Globalization;
  11. using MyAspNetMvcApp.Areas.Account.Models;
  12. using MyAspNetMvcApp.Areas.Account.ViewModels;
  13. using MyAspNetMvcApp.Models;
  14. using Microsoft.AspNet.Identity.EntityFramework;
  15. using Microsoft.AspNet.Identity;
  16. using System.Threading.Tasks;
  17. using MyAspNetMvcApp.Areas.Account.Controllers;
  18.  
  19. namespace MyAspNetMvcApp.Areas.Examples.Controllers
  20. {
  21.     public class ImportExcelController : Controller
  22.     {
  23.         // GET: Examples/ImportExcel
  24.         public ActionResult Index(HttpPostedFileBase ExcelFile)
  25.         {
  26.             var output = new List<StudentExcelViewModel>();
  27.             try
  28.             {
  29.                 if(ExcelFile != null)
  30.                 {
  31.                     var data = ExcelFile.ToFileByteArray();
  32.                     ImportFromExcel import = new ImportFromExcel();
  33.                     if(Path.GetExtension(ExcelFile.FileName.ToLower()) == ".xlsx")
  34.                         import.LoadXlsx(data);
  35.                     else if (Path.GetExtension(ExcelFile.FileName.ToLower()) == ".xls")
  36.                         import.LoadXls(data);
  37.                     else
  38.                     {
  39.                         TempData[BSMessage.TYPE] = BSMessage.MessageType.DANGER;
  40.                         TempData[BSMessage.DIALOGBOX] =  "Invalid Excel worksheet: " + Path.GetExtension(ExcelFile.FileName);
  41.                         return RedirectToAction("Index");
  42.                     }
  43.  
  44.                     output = import.ExcelToList<StudentExcelViewModel>(0, 1);
  45.  
  46.                     var duplicates = output.GroupBy(x => x.IdNumber)
  47.                                 .Select(g => new { Value = g.Key, Count = g.Count() })
  48.                                 .Where(h => h.Count > 1)
  49.                                 .Select(s => s.Value);
  50.  
  51.                     if(duplicates.Count() > 0)
  52.                     {
  53.                         TempData[BSMessage.TYPE] = BSMessage.MessageType.DANGER;
  54.                         TempData[BSMessage.PANEL] = "The following duplicate record/s has been removed: " + string.Join(", ", duplicates);
  55.                     }
  56.  
  57.                     output = output.GroupBy(x => x.IdNumber).Select(x => x.First()).ToList();
  58.  
  59.                     foreach (var stud in output)
  60.                     {
  61.                         Char[] separators = new Char[] { ',' }; // only the space character, in this case
  62.                         var names = stud.FullName.Split(separators);
  63.                         stud.FullName = names[0];
  64.                         separators = new Char[] { ' ' };
  65.                         stud.FirstName = names[1].Split(separators)[1];
  66.                     }
  67.                 }
  68.             }
  69.             catch
  70.             {
  71.             }
  72.  
  73.             return View(output);
  74.         }
  75.  
  76.         [HttpPost]
  77.         public async Task<ActionResult> BatchSubmit(string[] IdNumber, string[] FullName, string[] FirstName, string[] YearSection)
  78.         {
  79.             var students = new List<Models.Student>();
  80.  
  81.             try
  82.             {
  83.                 TextInfo textInfo = new CultureInfo("en-US", false).TextInfo;
  84.                 for (int i = 0; i < IdNumber.Length; i++)
  85.                 {
  86.                     var user = new ApplicationUser()
  87.                     {
  88.                         UserName = IdNumber[i],
  89.                         UserProfile = new UserProfile
  90.                         {
  91.                             UserName = IdNumber[i].Replace("-", string.Empty),
  92.                             RegistrationType = "student",
  93.                             LastName = textInfo.ToTitleCase(FullName[i].ToLower()),
  94.                             FirstName = textInfo.ToTitleCase(FirstName[i].ToLower()),
  95.                             RegistrationDate = DateTime.Now,
  96.                             IsActive = true,
  97.                             MetaData = Newtonsoft.Json.JsonConvert.SerializeObject(new { section = YearSection[i] })
  98.                         }
  99.                     };
  100.  
  101.                     var account = new AccountController();
  102.                     var result = await account.UserManager.CreateAsync(user, FullName[i].ToLower());
  103.                     if (result.Succeeded)
  104.                     {
  105.                         if (!string.IsNullOrEmpty(user.UserProfile.RegistrationType))
  106.                         {
  107.                             RegisterViewModel.AddRole(user.UserName, user.UserProfile.RegistrationType);
  108.                         }
  109.                     }
  110.  
  111.                     students.Add(new Models.Student()
  112.                     {
  113.                         IdNumber = IdNumber[i],
  114.                         LastName = textInfo.ToTitleCase(FullName[i].ToLower()),
  115.                         FirstName = textInfo.ToTitleCase(FirstName[i].ToLower()),
  116.                         YearSection = YearSection[i]
  117.                     });
  118.  
  119.                     //else
  120.                     //message += user.UserName + " / " + user.UserProfile.LastName + ", " + user.UserProfile.FirstName + " was not added. <br>";
  121.                 }
  122.  
  123.             }
  124.             catch (Exception ex)
  125.             {
  126.                 ViewData[BSMessage.TYPE] = BSMessage.MessageType.DANGER;
  127.                 ViewData[BSMessage.PANEL] = ex.GetBaseException().Message;
  128.             }
  129.  
  130.             return View(students);
  131.         }
  132.  
  133.         public ActionResult Delete(string IdNumber)
  134.         {
  135.             using (var db = new ExamplesDbContext())
  136.             {
  137.                 var stud = db.Students.Where(x => x.IdNumber == IdNumber).FirstOrDefault();
  138.                 db.Students.Remove(stud);
  139.                 db.SaveChanges();
  140.                 TempData[BSMessage.DIALOGBOX] = stud.FirstName + " " + stud.LastName + " has been deleted.";
  141.             }
  142.             return RedirectToAction("Index");
  143.         }
  144.     }
  145. }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement