Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read an excel file on asp.net core 1.0

Hello I`m trying to upload and read an excel file on my asp.net project but all the documentation I find is for ASP MVC 5. My goal is to read the excel sheet and pass the values to an list of objects.

This is my controller, it works for upload the file to my wwwroot/uploads

public class HomeController : Controller
{
    private IHostingEnvironment _environment;

    public HomeController(IHostingEnvironment environment)
    {
        _environment = environment;
    }

    public IActionResult index()
    {
        return View();
    }



    [HttpPost]
    public async Task<IActionResult> Index(ICollection<IFormFile> files)
    {
        var uploads = Path.Combine(_environment.WebRootPath, "uploads");
        foreach (var file in files)
        {
            if (file.Length > 0)
            {
                using (var fileStream = new FileStream(Path.Combine(uploads,    file.FileName), FileMode.Create))
                {
                    await file.CopyToAsync(fileStream);
                }
            }
        }
        return View();
    }
like image 291
Joel Avatar asked Nov 11 '16 23:11

Joel


2 Answers

Open the package manager console in Visual Studio and type:

PM> Install-Package EPPlus.Core

Writing files is then as simple as:

public void WriteExcel(string fileName)
{


    FileInfo file = new FileInfo(fileName);
    /// overwrite old file
    if (file.Exists)
    {
        file.Delete();
        file = new FileInfo(fileName);
    }
    using (ExcelPackage package = new ExcelPackage(file))
    {
        // add a new worksheet to the empty workbook
        ExcelWorksheet worksheet = package.Workbook.Worksheets.Add("Employee");
        worksheet.Cells["A1"].Value = "HELLO WORLD!!!";
        package.Save(); 
    }
}

More examples here: http://www.talkingdotnet.com/import-export-xlsx-asp-net-core/

like image 157
Tomáš Zato - Reinstate Monica Avatar answered Oct 06 '22 00:10

Tomáš Zato - Reinstate Monica


In .NET Core OleDb and DataTables are gone. This makes it harder for some projects to port themselves to netcore.

If you're reading OpenXml Excel files (xlsx), the unofficial Epplus.Core can help you.

But for the older 97-2003 formats (xls) we couldn't find a solution yet.

I would hope either NPOI or ExcelDataReader would get a core version later this year, but i don't see much activity on that direction.

like image 40
reiko Avatar answered Oct 06 '22 01:10

reiko