Hi rani,
Check this example. Now please take its reference and correct your code.
Excel file
Namespaces
using System.Data;
using System.IO;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Http;
using Microsoft.AspNetCore.Mvc;
using ClosedXML.Excel;
Controller
public class HomeController : Controller
{
private IHostingEnvironment Environment;
public HomeController(IHostingEnvironment _environment)
{
Environment = _environment;
}
public IActionResult Index()
{
return View();
}
[HttpPost]
public IActionResult Index(IFormFile postedFile)
{
string path = Path.Combine(this.Environment.WebRootPath, "Uploads");
if (!Directory.Exists(path))
{
Directory.CreateDirectory(path);
}
string fileName = Path.GetFileName(postedFile.FileName);
string filePath = Path.Combine(path, fileName);
using (FileStream stream = new FileStream(filePath, FileMode.Create))
{
postedFile.CopyTo(stream);
}
DataTable dt = new DataTable();
using (XLWorkbook workBook = new XLWorkbook(filePath))
{
IXLWorksheet workSheet = workBook.Worksheet(1);
bool firstRow = true;
foreach (IXLRow row in workSheet.Rows())
{
if (firstRow)
{
foreach (IXLCell cell in row.Cells())
{
dt.Columns.Add(cell.Value.ToString());
}
firstRow = false;
}
else
{
dt.Rows.Add();
int i = 0;
foreach (IXLCell cell in row.Cells())
{
dt.Rows[dt.Rows.Count - 1][i] = cell.Value.ToString();
i++;
}
}
}
}
dt.Columns.Add("Color");
foreach (DataRow dr in dt.Rows)
{
string country = dr["Country"].ToString();
switch (country.ToLower())
{
case "united states":
dr["Color"] = "Red";
break;
case "india":
dr["Color"] = "Orange";
break;
case "russia":
dr["Color"] = "Green";
break;
default:
dr["Color"] = "White";
break;
}
}
ViewBag.Data = dt;
System.IO.File.Delete(filePath);
return View();
}
}
View
@addTagHelper*, Microsoft.AspNetCore.Mvc.TagHelpers
@{
Layout = null;
}
<!DOCTYPE html>
<html>
<head>
<meta name="viewport" content="width=device-width" />
<title>Index</title>
<link rel="stylesheet" media="screen" href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.0.3/css/bootstrap.min.css" />
</head>
<body class="container">
<form method="post" asp-controller="Home" asp-action="Index" enctype="multipart/form-data">
<input type="file" name="postedFile" class="form-control" />
<input type="submit" value="Upload" class="btn btn-prinary" />
</form>
@if (ViewBag.Data != null)
{
<table class="table">
<tr>
<th>ID</th>
<th>Name</th>
<th>Country</th>
</tr>
@foreach (System.Data.DataRow dr in ViewBag.Data.Rows)
{
<tr>
<td>@dr["Id"]</td>
<td>@dr["Name"]</td>
<td style="background-color:@dr["Color"]">@dr["Country"]</td>
</tr>
}
</table>
}
</body>
</html>
Screenshot