How to Import CSV in ASP.NET MVC
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. Before getting started, ensure that you have the following: Open the Package Manager Console and run the following command to install the Create a class to handle the CSV importing logic. Let's call it In your MVC controller, use an instance of Create a view (e.g., 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.How to Import CSV in ASP.NET MVC
Introduction
Prerequisites
Step 1: Install Microsoft.VisualBasic NuGet Package
Microsoft.VisualBasic
NuGet package:
Install-Package Microsoft.VisualBasic
Step 2: Create a CSV Importer Class
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
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
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