ASP.NET MVC 5 - Import/Export CSV File

Import/export of any file type is the basic need of any development environment whether web development, desktop development or application development. In web development, import/export is commonly referred to as uploading/downloading of a file. I have recently created my own small import/export CSV file library CSVLibraryAK which is compatible with any C#.NET project of the 32-bit machine. The code of the library is open sourced, so, anyone can compile the code to target bit machines or to make new changes.
 
Today, I shall be demonstrating integration of CSVLibraryAK C#.NET library with ASP.NET MVC5 platform.
 

Web Development Import/Export CSV file Workflow

 
In web development importing/exporting of CSV files or any file, in general, are visualized as Uploading/Downloading of the files from the end user's perspective, i.e., the end-user will first upload his/her target CSV file to the web server. The web server, then, saves that CSV file in the CSV format and then imports that CSV file to target data structure into main memory for processing. Then, it exports the resultant data into a CSV format and then displays the uploaded/imported CSV file data to the end-user on the target web page. The end-user then downloads the CSV file which behind the scenes on the web server is already exported to a .CSV file format after processing of the uploaded CSV file. The resultant file is then available for the end user to download. 

Prerequisites
 
Following are some prerequisites before you proceed any further in this tutorial.
  1. Install CSVLibraryAK NuGet Package.
  2. Knowledge of ASP.NET MVC5.
  3. Knowledge of HTML.
  4. Knowledge of JavaScript.
  5. Knowledge of Bootstrap.
  6. Knowledge of jQuery.
  7. Knowledge of C# Programming.
You can download the complete source code for this tutorial. The sample code is being developed in Microsoft Visual Studio 2017 Professional.
 
Let's begin now.
 
Step 1
 
Create a new MVC web project and name it "MVCImportExportCSV". 
 
Step 2
 
Create a new "Controllers\HomeController.cs" file and add the following methods in it.
  1. //-----------------------------------------------------------------------  
  2. // <copyright file="HomeController.cs" company="None">  
  3. //     Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.  
  4. // </copyright>  
  5. // <author>Asma Khalid</author>  
  6. //-----------------------------------------------------------------------  
  7.   
  8. namespace MVCImportExportCSV.Controllers  
  9. {  
  10.     using System;  
  11.     using System.Collections.Generic;  
  12.     using System.Data;  
  13.     using System.IO;  
  14.     using System.Linq;  
  15.     using System.Web;  
  16.     using System.Web.Mvc;  
  17.     using CSVLibraryAK;  
  18.     using Models;  
  19.   
  20.     /// <summary>  
  21.     /// Home controller class.  
  22.     /// </summary>  
  23.     public class HomeController : Controller  
  24.     {        
  25.         #region Index view method.  
  26.   
  27.         ...  
  28.  
  29.         #region POST: /Home/Index  
  30.   
  31.         /// <summary>  
  32.         /// POST: /Home/Index  
  33.         /// </summary>  
  34.         /// <param name="model">Model parameter</param>  
  35.         /// <returns>Return - Response information</returns>  
  36.         [HttpPost]  
  37.         [AllowAnonymous]  
  38.         [ValidateAntiForgeryToken]  
  39.         public ActionResult Index(HomeViewModel model)  
  40.         {  
  41.             // Initialization.  
  42.             string importFilePath = string.Empty;  
  43.             string exportFilePath = string.Empty;  
  44.   
  45.             try  
  46.             {  
  47.                 // Verification  
  48.                 if (ModelState.IsValid)  
  49.                 {  
  50.                     // Converting to bytes.  
  51.                     byte[] uploadedFile = new byte[model.FileAttach.InputStream.Length];  
  52.                     model.FileAttach.InputStream.Read(uploadedFile, 0, uploadedFile.Length);  
  53.   
  54.                     // Initialization.  
  55.                     string folderPath = "~/Content/temp_upload_files/";  
  56.                     string filename = "download.csv";  
  57.   
  58.                     // Uploading file.  
  59.                     this.WriteBytesToFile(this.Server.MapPath(folderPath), uploadedFile, model.FileAttach.FileName);  
  60.   
  61.                     // Settings.  
  62.                     importFilePath = this.Server.MapPath(folderPath + model.FileAttach.FileName);  
  63.                     exportFilePath = this.Server.MapPath(folderPath + filename);  
  64.   
  65.                     // Impot CSV file.  
  66.                     model.Data = CSVLibraryAK.Import(importFilePath, model.HasHeader);  
  67.   
  68.                     // Export CSV file.  
  69.                     CSVLibraryAK.Export(exportFilePath, model.Data);  
  70.   
  71.                     // Deleting Extra files.  
  72.                     System.IO.File.Delete(importFilePath);  
  73.                 }  
  74.             }  
  75.             catch (Exception ex)  
  76.             {  
  77.                 // Info  
  78.                 Console.Write(ex);  
  79.             }  
  80.   
  81.             // Info  
  82.             return this.View(model);  
  83.         }  
  84.  
  85.         #endregion  
  86.  
  87.         #endregion  
  88.  
  89.         #region Download file methods  
  90.  
  91.         #region GET: /Home/DownloadFile  
  92.   
  93.         /// <summary>  
  94.         /// GET: /Home/DownloadFile  
  95.         /// </summary>  
  96.         /// <returns>Return download file</returns>  
  97.         public ActionResult DownloadFile()  
  98.         {  
  99.             // Model binding.  
  100.             HomeViewModel model = new HomeViewModel { FileAttach = null, Data = new DataTable(), HasHeader = true };  
  101.   
  102.             try  
  103.             {  
  104.                 // Initialization.  
  105.                 string filePath = "~/Content/temp_upload_files/download.csv";  
  106.   
  107.                 // Info.  
  108.                 return this.GetFile(filePath);  
  109.             }  
  110.             catch (Exception ex)  
  111.             {  
  112.                 // Info  
  113.                 Console.Write(ex);  
  114.             }  
  115.   
  116.             // Info.  
  117.             return this.View(model);  
  118.         }  
  119.  
  120.         #endregion  
  121.  
  122.         #endregion  
  123.   
  124.         ...  
  125.     }  

In the above code, I have created POST "Index(...)" method which will receive uploaded CSV file input from the end-user, then save the CSV file on the web server, then import the stored CSV file using CSVLibraryAK library, then process the import file if applicable, then save & export the resultant CSV file on the web server using CSVLibraryAK library, and finally, display the result of CSV file on the web page. I have also created the DownloadFile(...) method which will return the resultant CSV file after processing back to the end-user.
 
Step 3
 
Create a simple view to upload a file. Then, display the resultant data and also provide the export feature to download the resultant data.
 
Step 4
 
Now, execute the project and you will be able to see the following in action i.e.:
 




 
 
 

Conclusion

 
In this article, you learned to integrate CSVLibraryAK C#.NET library with ASP.NET MVC5. You also learned to upload CSV file to the web server. You also learned to utilize CSVLibraryAK.Import(...) method. You also learned to download the CSV file and you also learned to utilize CSVLibraryAK.Export() method.


Similar Articles