Click here to Skip to main content
15,498,966 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
It's a ASP.NET Core MVC. I want to upload an excel file so I can view it in a List View, but I am stuck there. User is supposed to upload the file and then populate it in the list.

I previously wrote it on MVC, and I'm rewriting it in ASP.NET MVC Core. It's different since some code that I wrote for the MVC5 didn't work for Core, and I am stuck.

What I have tried:

Part of my List view:
<form asp-controller="Staff" asp-action="Upload" method="post" enctype="multipart/form-data">
    <input type="file" name="file" />
    <br/>
    <button type="Submit">Upload</button>
    <h1>Status: @ViewData["message"]</h1>
    
</form>


And this is my upload code.
[HttpPost]
public ActionResult Upload(IFormFile file, [FromServices] IHostingEnvironment oHE)
{
    string fileName = $"{oHE.WebRootPath}\\UploadedFiles\\{file.FileName}";


    //-----I am stuck within this point.----

    //Execute loop over rows
        foreach(string row in csvData.Split('\n'))
        {
            if(!string.IsNullOrEmpty(row))
            {
                buses.Add(new Bus
                {
                    model = row.Split(',')[0],
                    bodyWork = row.Split(',')[1],
                    emissionStandard = Convert.ToInt32(row.Split(',')[2]),
                    year = Convert.ToInt32(row.Split(',')[3])
                });
            }
        }

    return View(new List<Staff>());
}


Help is appreciated.
Posted
Updated 28-Nov-21 23:24pm

1 solution

Your question is not entirely clear. If you want to read the lines from the uploaded file, you just need to open the stream and read the file:
C#
using (var fileStream = file.OpenReadStream())
using (var reader = new StreamReader(fileStream))
{
    string row;
    while ((row = reader.ReadLine()) != null)
    {
        ... Process the row here ...
    }
}
IFormFile.OpenReadStream Method (Microsoft.AspNetCore.Http) | Microsoft Docs[^]
StreamReader Class (System.IO) | Microsoft Docs[^]
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900