This article demonstrates
In your MVC razor view add the below HTML content:
@using(Html.BeginForm("Upload", "Home", FormMethod.Post, new {enctype = "multipart/form-data"}))
{
<
table
>
tr
td
>File:</
input
type
=
"file"
name
"UploadedFile"
/>
</
colspan
"2"
"submit"
"Submit"
value
}
Notice, the action name : Upload, Controller Name: Home.
Now come to home controller and add action called Upload.
public ActionResult Upload(FormCollection formCollection)
public
ActionResult Upload(FormCollection formCollection)
if (Request != null)
if
(Request !=
null
)
HttpPostedFileBase file = Request.Files["UploadedFile"];
HttpPostedFileBase file = Request.Files[
];
if ((file != null) && (file.ContentLength > 0) && !string.IsNullOrEmpty(file.FileName))
((file !=
) && (file.ContentLength > 0) && !
string
.IsNullOrEmpty(file.FileName))
string fileName = file.FileName;
fileName = file.FileName;
string fileContentType = file.ContentType;
fileContentType = file.ContentType;
byte[] fileBytes = new byte[file.ContentLength];
byte
[] fileBytes =
new
[file.ContentLength];
var data = file.InputStream.Read(fileBytes, 0, Convert.ToInt32(file.ContentLength));
Now try to run the app by putting a breakpoint and see if all is working until now.
Now add dll called EPPLUS from NuGet which is used for reading and writing files.
Lets say I have file with FirstName & LastName.
Now add a class called users.
class
Users {
FirstName {
get
;
set
; }
LastName {
; } }
Now lets modify our action method to read the file stream
object
which we uploaded. Add
using
OfficeOpenXml; statement
var usersList =
List<Users>();
(var package =
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++)
var user =
Users();
user.FirstName = workSheet.Cells[rowIterator, 1].Value.ToString();
user.LastName = workSheet.Cells[rowIterator, 2].Value.ToString();
usersList.Add(user);
return
View(
"Index"
);
Finally, all the users will be available in usersList object.