How to Import CSV in ASP.NET MVC | Code2night.com
Code2night
  • Home
  • Blogs
  • Guest Posts
  • Tutorial
  • Post Blog
  • Register
  • Login
  1. Home
  2. Blogpost

How to Import CSV in ASP.NET MVC

Date- Feb 02,2024

2279

Free Download Pay & Download

How to Import CSV in ASP.NET MVC

Introduction

In this tutorial, we will learn how to import data from a CSV file into a DataTable in an ASP.NET MVC application. We will use C# code to read the CSV file and populate a DataTable, and then display the DataTable in a view.

Prerequisites

Before getting started, ensure that you have the following:

  • Visual Studio with ASP.NET MVC installed.
  • An ASP.NET MVC project created.
  • A CSV file with data (for example, "data.csv").

Step 1: Install Microsoft.VisualBasic NuGet Package

Open the Package Manager Console and run the following command to install the Microsoft.VisualBasic NuGet package:

                
                    Install-Package Microsoft.VisualBasic
                
            

Step 2: Create a CSV Importer Class

Create a class to handle the CSV importing logic. Let's call it CsvImporter:

                
                    using System;
                    using System.Collections.Generic;
                    using System.Data;
                    using Microsoft.VisualBasic.FileIO;

                    public class CsvImporter
                    {
                        public DataTable ReadCsv(string filePath)
                        {
                            DataTable dataTable = new DataTable();

                            try
                            {
                                using (TextFieldParser parser = new TextFieldParser(filePath))
                                {
                                    parser.Delimiters = new string[] { "," };
                                    parser.HasFieldsEnclosedInQuotes = true;

                                    // Read the column names from the first line of the CSV file
                                    string[] headers = parser.ReadFields();
                                    foreach (string header in headers)
                                    {
                                        dataTable.Columns.Add(header);
                                    }

                                    // Read the remaining lines and add data to the DataTable
                                    while (!parser.EndOfData)
                                    {
                                        string[] fields = parser.ReadFields();
                                        dataTable.Rows.Add(fields);
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                // Handle exceptions
                                Console.WriteLine($"Error reading CSV file: {ex.Message}");
                            }

                            return dataTable;
                        }
                    }
                
            

Step 3: Use the CsvImporter in the Controller

In your MVC controller, use an instance of CsvImporter to read the CSV file and pass the resulting DataTable to the view:

using System;
using System.Collections.Generic;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace ImportCSVData.Controllers
{
    public class HomeController : Controller
    {
        public ActionResult Index()
        {
            // Specify the path to your CSV file
            string csvFilePath = Server.MapPath("~/Content/Sample.csv");

            CsvImporter csvImporter = new CsvImporter();
            DataTable dataTable = csvImporter.ReadCsv(csvFilePath);

            return View(dataTable);
        }

    
    }
}
                
            

Step 4: Create a View to Display DataTable

Create a view (e.g., Index.cshtml) to display the DataTable:

                
                    @model System.Data.DataTable
                    @using System.Data
                    @{
                        ViewBag.Title = "CSV Import";
                    }

                    <h2>CSV Import</h2>

                    @if (Model != null)
                    {
                        <table border="1">
                            <tr>
                                @foreach (DataColumn column in Model.Columns)
                                {
                                    <th>@column.ColumnName</th>
                                }
                            </tr>

                            @foreach (DataRow row in Model.Rows)
                            {
                                <tr>
                                    @foreach (var cell in row.ItemArray)
                                    {
                                        <td>@cell.ToString()</td>
                                    }
                                </tr>
                            }
                        </table>
                    }
                    else
                    {
                        <p>No data available.</p>
                    }
                
            

Conclusion

Congratulations! You have successfully imported data from a CSV file into a DataTable in your ASP.NET MVC application. Feel free to customize the code according to your specific requirements.

You can run the application and you will be see csv data on the view in list format. So this is how to import csv data using asp.net mvc.

Comments

Tags

LinkedinLogin
LinkedinProfile
GetLinkedinProfile
C#
Aspnet
MVC
Linkedin
ITextSharp
Export to Pdf
AspNet Core
AspNet
View to Pdf in Aspnet
Model Validation In ASPNET Core MVC 60
Model Validation
Model Validation In ASPNET Core MVC
Model Validation In ASPNET
Image Compression in AspNet
Compress Image in c#
AspNet MVC
Free Download for Youtube Subscribers!

First click on Subscribe Now and then subscribe the channel and come back here.
Then Click on "Verify and Download" button for download link

Subscribe Now | 1190
Download
Support Us....!

Please Subscribe to support us

Thank you for Downloading....!

Please Subscribe to support us

Continue with Downloading
Be a Member
Join Us On Whatsapp Join Us On Facebook

Welcome To Code2night, A common place for sharing your programming knowledge,Blogs and Videos

  • Panipat
  • info@Code2night.com

Links

  • Home
  • Blogs
  • Tutorial
  • Post Blog

Popular Tags

Copyright © 2025 by Code2night. All Rights Reserved

  • Home
  • Blog
  • Login
  • SignUp
  • Contact
  • Terms & Conditions
  • Refund Policy
  • About Us
  • Privacy Policy
  • Json Beautifier
  • Guest Posts