Search This Blog

Thursday 29 June 2017

Upload File In ASP.NET MVC

Read Excel File in ASP.NET MVC

View
@{
    ViewBag.Title = "FileUpload";
}
<h2>
    FileUpload</h2>
@using (Html.BeginForm("FileUpload""Upload"FormMethod.Post, new { @enctype = "multipart/form-data" }))
{
    <input name="uploadfile" type="file" />
    @Html.ValidationMessage("uploadfile""")
    <br />
    <input type="submit" value="Upload" />
}

Controller
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.Data.OleDb;
using System.Data;
using System.Text;

namespace MvcApplication1.Controllers
{
    public class UploadController : Controller
    {
        //
        // GET: /Upload/

        public ActionResult FileUpload()
        {
            return View();
        }

        [HttpPost]
        public ActionResult FileUpload(HttpPostedFileBase uploadfile)
        {
            string ext = string.Empty;
            string fileName = string.Empty;
            string filePath = string.Empty;
            string strConnectionString = string.Empty;

            OleDbConnection con = null;
            OleDbCommand cmd = null;
            OleDbDataAdapter da = null;
            DataSet ds = null;
            StringBuilder sb = null;

            // validate file
            if (uploadfile == null)
            {
                ModelState.AddModelError("uploadfile""Please select file to upload.");
            }
            else
            {
                ext = Path.GetExtension(uploadfile.FileName);
                ext = ext.ToLower();

                if (!(ext.Equals(".xls") || ext.Equals(".xlsx")))
                {
                    ModelState.AddModelError("uploadfile""Please upload .xls / .xlsx files only.");
                }
            }

            // Check validation ok
            if (ModelState.IsValid)
            {

                // Get file name
                fileName = Path.GetFileName(uploadfile.FileName);

                // Save file in root folder
                filePath = Path.Combine(Server.MapPath("~/UploadedFiles"), fileName);
                uploadfile.SaveAs(filePath);

                // based on file extension define connection string
                if (ext.Equals(".xls"))
                {
                    strConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + filePath + ";Extended Properties=Excel 8.0";
                }
                else
                {
                    if (ext.Equals(".xlsx"))
                    {
                        strConnectionString = "Provider=Microsoft.ACE.OLEDB.12.0;Data Source=" + filePath + ";Extended Properties=Excel 12.0";
                    }
                }

                // create connection string
                using (con = new OleDbConnection(strConnectionString))
                {
                    // Open connection
                    con.Open();

                    // Get all sheet in excel file
                    DataTable Sheets = con.GetOleDbSchemaTable(OleDbSchemaGuid.Tables, null);

                    // getting first sheet name only
                    string worksheets = Sheets.Rows[0]["TABLE_NAME"].ToString();

                    // create select query
                    string query = string.Format("SELECT * FROM [{0}]", worksheets);

                    cmd = new OleDbCommand(query, con);
                    da = new OleDbDataAdapter(cmd);
                    ds = new DataSet();
                    da.Fill(ds);
                }
            }

            return View("FileUpload");
        }
    }
}

Note:- 
Create “UploadedFiles” folder in application root.

No comments:

Post a Comment