1
Reply

excel data reader read excel file and data add my list

mahmudur rifat

mahmudur rifat

Jul 16 2016 2:41 AM
377
my project mvc 4.i am upload excel file then show data table,i want data table data bind my list and show combo box how can is possible. Below in my code:\
 
using Excel;
using Office_Project.Models;
using System;
using System.Collections.Generic;
using System.Data;
using System.IO;
using System.Linq;
using System.Web;
using System.Web.Mvc;

namespace Office_Project.Controllers
{
public class FileController : Controller
{

public ActionResult Index()
{
return View();
}
public ActionResult Upload()
{
return View();
}

[HttpPost]
[ValidateAntiForgeryToken]
public ActionResult Upload(HttpPostedFileBase upload)
{
List<SEfile> sefile = new List<SEfile>();
if (ModelState.IsValid)
{

if (upload != null && upload.ContentLength > 0)
{
// ExcelDataReader works with the binary Excel file, so it needs a FileStream
// to get started. This is how we avoid dependencies on ACE or Interop:
Stream stream = upload.InputStream;

// We return the interface, so that
IExcelDataReader reader = null;


if (upload.FileName.EndsWith(".xls"))
{
reader = ExcelReaderFactory.CreateBinaryReader(stream);
}
else if (upload.FileName.EndsWith(".xlsx"))
{
reader = ExcelReaderFactory.CreateOpenXmlReader(stream);
}
else
{
ModelState.AddModelError("File", "This file format is not supported");
return View();
}

reader.IsFirstRowAsColumnNames = true;

DataSet result = reader.AsDataSet();

//return View(result.Tables[0]);


while (reader.Read())
{
SEfile p = new SEfile();
p.BankName = (reader[1].ToString());
p.BankBranch = (reader[2].ToString());

}
reader.Close();
}
else
{
ModelState.AddModelError("File", "Please Upload Your file");
}

}
return View("Upload");
}

}

Answers (1)