Header Ads

ASP.NET MVC5: 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 upload/download 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 32 bit machine. The code of the library is open sourced, so, anyone can compile the code to target bit machine 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 import/export of CSV files or any file in general are visualized as Upload/Download of the files from the end-user's perspective i.e. end-user will first upload his/her target CSV file to the web server, web server then saves that CSV file in .CSV format and then import that .CSV file to target data structure into main memory for processing, then 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 example code is being developed in Microsoft Visual Studio 2017 Professional.

Download Now!

Let's begin now.

1) Create a new MVC web project and name it "MVCImportExportCSV".  

2) Create a new "Controllers\HomeController.cs" file and add following methods in it i.e.

//-----------------------------------------------------------------------
// <copyright file="HomeController.cs" company="None">
//     Copyright (c) Allow to distribute this code and utilize this code for personal or commercial purpose.
// </copyright>
// <author>Asma Khalid</author>
//-----------------------------------------------------------------------

namespace MVCImportExportCSV.Controllers
{
    using System;
    using System.Collections.Generic;
    using System.Data;
    using System.IO;
    using System.Linq;
    using System.Web;
    using System.Web.Mvc;
    using CSVLibraryAK;
    using Models;

    /// <summary>
    /// Home controller class.
    /// </summary>
    public class HomeController : Controller
    {      
        #region Index view method.

        ...

        #region POST: /Home/Index

        /// <summary>
        /// POST: /Home/Index
        /// </summary>
        /// <param name="model">Model parameter</param>
        /// <returns>Return - Response information</returns>
        [HttpPost]
        [AllowAnonymous]
        [ValidateAntiForgeryToken]
        public ActionResult Index(HomeViewModel model)
        {
            // Initialization.
            string importFilePath = string.Empty;
            string exportFilePath = string.Empty;

            try
            {
                // Verification
                if (ModelState.IsValid)
                {
                    // Converting to bytes.
                    byte[] uploadedFile = new byte[model.FileAttach.InputStream.Length];
                    model.FileAttach.InputStream.Read(uploadedFile, 0, uploadedFile.Length);

                    // Initialization.
                    string folderPath = "~/Content/temp_upload_files/";
                    string filename = "download.csv";

                    // Uploading file.
                    this.WriteBytesToFile(this.Server.MapPath(folderPath), uploadedFile, model.FileAttach.FileName);

                    // Settings.
                    importFilePath = this.Server.MapPath(folderPath + model.FileAttach.FileName);
                    exportFilePath = this.Server.MapPath(folderPath + filename);

                    // Impot CSV file.
                    model.Data = CSVLibraryAK.Import(importFilePath, model.HasHeader);

                    // Export CSV file.
                    CSVLibraryAK.Export(exportFilePath, model.Data);

                    // Deleting Extra files.
                    System.IO.File.Delete(importFilePath);
                }
            }
            catch (Exception ex)
            {
                // Info
                Console.Write(ex);
            }

            // Info
            return this.View(model);
        }

        #endregion

        #endregion

        #region Download file methods

        #region GET: /Home/DownloadFile

        /// <summary>
        /// GET: /Home/DownloadFile
        /// </summary>
        /// <returns>Return download file</returns>
        public ActionResult DownloadFile()
        {
            // Model binding.
            HomeViewModel model = new HomeViewModel { FileAttach = null, Data = new DataTable(), HasHeader = true };

            try
            {
                // Initialization.
                string filePath = "~/Content/temp_upload_files/download.csv";

                // Info.
                return this.GetFile(filePath);
            }
            catch (Exception ex)
            {
                // Info
                Console.Write(ex);
            }

            // Info.
            return this.View(model);
        }

        #endregion

        #endregion

        ...
    }
}

In the above code, I have created POST "Index(...)" method which will receive upload 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.

3) Create a simple view to upload a file then display the resultant data and also provide export feature to download the resultant data.

4) Now, execute the project and you will be able to see the following in action i.e.


 
 


Conclusion

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

1 comment: