How to Import/Export Data From Excel In MVC

In software development, Import/Export is a technique to read and write data from files. We have multiple data file format to store our valuable data like png, jpg, xls, xlsx, pdf, txt, sql, etc, from where we need to read and write data. Every technology has its own technique to read and write data from files. Here, I am using the c# programming language to perform this task through ASP.NET MVC Web Application.

Jump to Section

Download Demo Application

Create Application

Note: I am using visual studio 2013, Follow the steps to create your application for Import and export excel file data.

Step 1 :

Note: If a new window is open then select Empty then Click Ok.

Now, new Empty MVC application is created successfully.

Step 2 :

 public int id public string Expectation 

Step 3 :

Step 4 :

You can easily find and include this library via NuGet within your application as well through the following steps:

Both of these approaches will add the appropriate Excel assembly references to your application. Then when you actually need to execute a query within your code, you might use something like this:

// Reference to access the appropriate ExcelReader classes using Excel;

Step 5 :

Add the following code to ExcelData.cs class.

string _path; public ExcelData(string path) < _path = path; >public IExcelDataReader getExcelReader() < // ExcelDataReader works with the binary Excel file, so it needs a FileStream // to get started. This is how we avoid dependencies on ACE or Interop: FileStream stream = File.Open(_path, FileMode.Open, FileAccess.Read); // // We return the interface, so that IExcelDataReader reader = null; try < if (_path.EndsWith(".xls")) < reader = ExcelReaderFactory.CreateBinaryReader(stream); >if (_path.EndsWith(".xlsx")) < reader = ExcelReaderFactory.CreateOpenXmlReader(stream); >if (_path.EndsWith(".ods")) < reader = ExcelReaderFactory.CreateBinaryReader(stream); >return reader; > catch (Exception) < throw; >> public IEnumerable getWorksheetNames() < var reader = this.getExcelReader(); var workbook = reader.AsDataSet(); var sheets = from DataTable sheet in workbook.Tables select sheet.TableName; return sheets; >public IEnumerable getData(string sheet, bool firstRowIsColumnNames = true) < var reader = this.getExcelReader(); reader.IsFirstRowAsColumnNames = firstRowIsColumnNames; //string SheetName = getWorksheetNames().FirstOrDefault(); var workSheet = reader.AsDataSet().Tables[sheet]; var filteredRows = workSheet.Rows.Cast().Where(row => row.ItemArray.Any(field => !(field is System.DBNull))); // TTliteUtil.Util.WriteToEventLog("Sheet read: "+workSheet.ToString()); var rows = from DataRow a in filteredRows select a; return rows; >

Step 6 :

Step 7 :

Reference to access the model classes

using Export_Excel.Models;
using System.IO; using System.Data; 
 public ActionResult Index()   ViewBag.EmployeeList = ""; return View(); >
public ActionResult Import(FormCollection formCollection)   if (Request != null)   DataTable dt = new DataTable(); HttpPostedFileBase file = Request.Files["UploadedFile"]; if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))   string fileName = file.FileName; string path = Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["XlsFilePath"] + fileName); file.SaveAs(path); if (!System.IO.Directory.Exists(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["XlsFilePath"])))   System.IO.Directory.CreateDirectory(Server.MapPath(System.Configuration.ConfigurationManager.AppSettings["XlsFilePath"])); > var excelData = new ExcelData(path); var sData = excelData.getData("Sheet1"); List list = new List(); dt = sData.CopyToDataTable(); foreach (DataRow item in dt.Rows)   Employee emp = new Employee(); emp.id = Convert.ToInt32(item["id"]); emp.Expectation = item["Expectation"].ToString(); list.Add(emp); > ViewBag.EmployeeList = list; TempData["EmployeeList"] = list; > > return View("Index"); >
public ActionResult Export()   List emps = TempData["EmployeeList"] as List; var grid = new System.Web.UI.WebControls.GridView(); grid.DataSource = emps; grid.DataBind(); Response.ClearContent(); Response.Buffer = true; Response.AddHeader("content-disposition", "attachment; filename=Expectations.xls"); Response.ContentType = "application/ms-excel"; Response.Charset = ""; StringWriter sw = new StringWriter(); HtmlTextWriter htw = new HtmlTextWriter(sw); grid.RenderControl(htw); Response.Output.Write(sw.ToString()); Response.Flush(); Response.End(); ViewBag.EmployeeList = emps; return View("Index"); >

Step 8 :

  • Add a view, Right click on Index method > Add view > Click Add button.
  • Replace the Index.cshtml content with the following content.
@using Export_Excel.Models;
@  ViewBag.Title = "Index"; > @using (Html.BeginForm("Import", "Home", FormMethod.Post, new < enctype = "multipart/form-data" >))     Select File :        Import Data :       > 
@using (Html.BeginForm("Export", "Home")) Export Data : >
@ @foreach (var l in list) @l.id @l.Expectation >

Step 9 :

  • Create an Excel file with two column “Id” and “Expectation“.
  • Add some data in excel sheet.
Id Expectation
1 Acknowledge emails within 2 hours
2 Be prepared for Daily Stand-up at 10:15 am
3 Commit code updates to repository daily
4 Ensuring the timely delivery of work as per quality standards.
5 Every update to production server must be signed off by QA
6 Follow variable naming conventions & guidelines for the particular platform.
7 Have 90% understanding of the project through SRS doc before commencing work.
8 Maintain politeness while talking to other colleagues
9 No use of social media either with phone or desktop.
10 Provide Developer Sign Off before handing over builds to QA
  • Save excel sheet where you want to save.

Step 10 :

  • Build your application.
  • Run the application.
  • Your Index.cshtml user interface looks like the following result.

Step 11 :

  • Click “Choose file” button.
  • Go to the file location where your excel file is saved.
  • Select Excel file.
  • Click ok.

Step 12 :

  • Click Import from Excel button for import data from excel sheet and bind with HTML table.
  • The following UI is shown, After clicking on Import from Excel button.

Step 13 :

  • Click “Export to Excel” button for export data from HTML table.
  • When you click on “Export to Excel” button excel sheet will automatically download to your system.
  • Open your excel file and match your records from excel sheet to HTML table, data will be same.
  • Enjoy! have a great day.

Summary

I hope, this article would help you to understand about Import and Export data from Excel or HTML. In the end, You are expert in managing data from Excel sheet in MVC Application.

Reference article:

  • Input-Output File Stream: How to work with File Input/Output Stream classes?
  • Encryption-Decryption: How to perform same Encryption and Decryption in C# and Node JS?
  • Kendo-Grid: How to work with Kendo Grid using Jquery?
  • Angular-CLI: How to work with Angular CLI (Command Line Interface)?