Wednesday, 8 June 2016

How to read CSV file in MVC using/LumenWorksCsvReader

Install nugget package in user appliction

View


 

@{
    ViewBag.Title = "Index";
}
<br /><br /><br />
@using (Html.BeginForm("Save", "Home", FormMethod.Post, new { @enctype = "multipart/form-data" }))
{
    @Html.TextBox("fu", null, new { @type = "file" }) <br />
    <input type="submit" value="Save" />
}


Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using LumenWorks.Framework.IO.Csv;
using System.IO;

namespace WebApplication18.Controllers
{
    public class HomeController : Controller
    {
        // GET: Home
        public ActionResult Index()
        {
            return View();
        }
        [HttpPost]
        public ActionResult Save(HttpPostedFileBase fu)
        {

            fu.SaveAs(Server.MapPath("~/File/" + System.IO.Path.GetFileName(fu.FileName)));
            Readcsv(Server.MapPath("~/File/" + System.IO.Path.GetFileName(fu.FileName)));
            return RedirectToAction("Index");
        }
        public void Readcsv(string Path)
        {
            using (CsvReader csv = new CsvReader(
                   new StreamReader(Path), true, '\t', '\0', '\0', '#', ValueTrimmingOptions.All))
            {
                csv.MissingFieldAction = MissingFieldAction.ReplaceByNull;
                string[] headers = csv.GetFieldHeaders();
                while (csv.ReadNextRecord())
                {
                    var y = csv[0];
                    for (int i = 0; i < csv.FieldCount; i++)
                    {
                        var x = csv[i];
                    }
                        
                }
            }
        }
    }
}

No comments:

Post a Comment