Best way to Read Excel Files with MVC
There of course are multiple ways to upload and read an Excel file. After creating a version the long way I ran into file storage, permission issues etc so started looking for a better way to do this. I found a solution that does not actually upload the excel file, so no storage issues, no permission issues ... and a lot less code. I am using a package available from Nuget called EPPlus. So first thing you will want to do is grab this package - here is the nuget command line:
install-package EPPlus Be sure and add this to your Controller: using OfficeOpenXml;
public ActionResult UploadExtensions(HttpPostedFileBase file)
{
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
{
string fileName = file.FileName;
string fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
}
int itemcount = 0; using (var package = new ExcelPackage(file.InputStream)) { var currentSheet = package.Workbook.Worksheets; var workSheet = currentSheet.First(); var noOfCol = workSheet.Dimension.End.Column; var noOfRow = workSheet.Dimension.End.Row; for (int rowIterator = 2; rowIterator <= noOfRow; rowIterator++) {
//the following code is specific to my app but wanted to show you the iteration
ExtensionUpload c = new ExtensionUpload();
c.AccountCode = workSheet.Cells[rowIterator, 1].Value.ToString();
c.ExtensionURL = workSheet.Cells[rowIterator, 2].Value.ToString();
//here is an example of how I deal with a null value
if (workSheet.Cells[rowIterator, 3].Value != null)
{
c.StoreExtension = workSheet.Cells[rowIterator, 3].Value.ToString();
c.StoreExtension = c.StoreExtension.PadLeft(2, '0');
}
else
{
c.StoreExtension = "00";
}
//adding the record to my database object
db.ExtensionUploads.Add(c);
itemcount += 1;
}
db.SaveChanges();
ViewBag.message = itemcount + " Records were inserted! ";
return View();
}
Comments