Controller Code:
public ActionResult Upload()
{
return View(“FileUpload”);
}
[AcceptVerbs(HttpVerbs.Post)]
public string Upload(HttpPostedFileBase uploadFile)
{
StringBuilder strValidations = new StringBuilder(string.Empty);
try
{
if (uploadFile.ContentLength > 0)
{
string filePath = Path.Combine(HttpContext.Server.MapPath(“../Uploads”),
Path.GetFileName(uploadFile.FileName));
uploadFile.SaveAs(filePath);
DataSet ds = new DataSet();
A 32-bit provider which enables the use of
string ConnectionString = “Provider=Microsoft.ACE.OLEDB.12.0;Data Source=” + Server.MapPath(“../Uploads/”) + uploadFile.FileName.Split(‘\\’)[3].ToString() + “;Extended Properties=Excel 12.0;”;
using (OleDbConnection conn = new System.Data.OleDb.OleDbConnection(ConnectionString))
{
conn.Open();
using (DataTable dtExcelSchema = conn.GetSchema(“Tables”))
{
string sheetName = dtExcelSchema.Rows[0][“TABLE_NAME”].ToString();
string query = “SELECT * FROM [” + sheetName + “]”;
OleDbDataAdapter adapter = new OleDbDataAdapter(query, conn);
DataSet ds = new DataSet();
adapter.Fill(ds, “Items”);
if (ds.Tables.Count > 0)
{
if (ds.Tables[0].Rows.Count > 0)
{
for (int i = 0; i < ds.Tables[0].Rows.Count; i++)
{
///// Do required action ////
}
}
}
}
}
}
//// Braces count may vary
Code in View:
<div><% using (Html.BeginForm(“Upload”, “Rules”, FormMethod.Post, new { enctype = “multipart/form-data” }))
{%>
Upload File Here <input name=”uploadFile” type=”file” /> <input type=”submit” value=”UploadFile” title=”Upload File” onclick =”return CheckFileName();” />
<%} %></div>
Upload File Here
<!– CheckFileName(); A simple js function to check the file extension… To be added in Content2 of your Content Place holder…
function CheckFileName() {
var fileName = document.getElementById(“uploadFile”).value
//debugger;
if (fileName == “”) {
alert(“Browse to upload a valid File with xls / xlsx extension”);
return false;
}
else if (fileName.split(“.”)[1].toUpperCase() == “XLS” || fileName.split(“.”)[1].toUpperCase() == “XLSX”)
return true;
else {
alert(“File with ” + fileName.split(“.”)[1] + ” is invalid. Upload a validfile with xls / xlsx extensions”);
return false;
}
return true;
}
very usefull,thank’s so much !!!!
Its really good 🙂 and it is very usefull for me also.