In software applications, sometimes a user needs to export or import the data in Excel format in order to perform several operations. In this article, we will learn how to export and import an Excel file with ClosedXML package in ASP.NET MVC.
ClosedXML is a .NET Library for writing and manipulating the Excel 2007+ files. It’s available free on GitHub to use for the commercial project. For more details,
click here to view the license on GitHub.
Import or Read Excel File
Let’s begin!
Create a new empty ASP.NET MVC web project in Visual Studio and install the ClosedXML library from NuGet Package Manager.
After that, add an Empty Controller, i.e., HomeController in the project. Add the below code in the Controller.
- public ActionResult UploadExcel() {
- return View();
- }
-
- [HttpPost]
- public ActionResult UploadExcel(HttpPostedFileBase file)
- {
- DataTable dt = new DataTable();
-
- if (file != null && file.ContentLength>0 && System.IO.Path.GetExtension(file.FileName).ToLower()==".xlsx") {
- string path = Path.Combine(Server.MapPath("~/UploadFile"), Path.GetFileName(file.FileName));
-
- file.SaveAs(path);
-
- using (XLWorkbook workbook=new XLWorkbook(path)) {
- IXLWorksheet worksheet= workbook.Worksheet(1);
- bool FirstRow = true;
-
- string readRange = "1:1";
- foreach (IXLRow row in worksheet.RowsUsed()) {
-
- if (FirstRow)
- {
-
- readRange = string.Format("{0}:{1}", 1, row.LastCellUsed().Address.ColumnNumber);
- foreach (IXLCell cell in row.Cells(readRange)) {
- dt.Columns.Add(cell.Value.ToString());
- }
- FirstRow = false;
- }
- else {
-
- dt.Rows.Add();
- int cellIndex = 0;
-
- foreach (IXLCell cell in row.Cells(readRange))
- {
- dt.Rows[dt.Rows.Count - 1][cellIndex] = cell.Value.ToString();
- cellIndex++;
- }
- }
- }
-
- if (FirstRow) {
- ViewBag.Message = "Empty Excel File!";
- }
- }
- }
- else
- {
-
- ViewBag.Message = "Please select file with .xlsx extension!";
- }
- return View(dt);
- }
The GET action of "Upload Excel Action" will return a View as shown in the below image. And, in the POST action method, we are checking the file, its content length, and extension. We will show a message to the user if an incorrect file is uploaded with the help of ViewBag. In UploadExcel.cshtml View, we have added a file control with a Submit button so that we can post that file. For demonstration, we are reading the Excel file and writing its data in the DataTable (You can bind that with a list or model whatever fits with your project or as per your project requirement) and returning the DataTable to the View directly in order to show the content of the Excel document.
UploadExcel.cshtml code
- @using System.Data
- @model DataTable
- @{
- Layout = null;
- }
-
- <!DOCTYPE html>
-
- <html>
- <head>
- <meta name="viewport" content="width=device-width" />
- <title>ReadExcelFile</title>
- <style>
- table {
- border: 1px solid #000000;
- text-align: left;
- border-collapse: collapse;
- margin-top:20px;
- }
-
- table td, table th {
- border: 1px solid #000000;
- padding: 5px 4px;
- }
-
- table th {
- background-color: #5396d2;
- color:white;
- }
- </style>
- </head>
- <body>
- @using (Html.BeginForm("UploadExcel", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
- {
- <div>
- <label>Upload File:</label>
- <input type="file" id="file" name="file" />
- <input type="submit" value="Upload File" />
- </div>
- <!--Display Error Message-->
- <div style="color:red;">@ViewBag.Message</div>
- <!--Show the Data Table on the View after reading the Excel File-->
- if (Model != null)
- {
-
- <table>
- <tr>
- @for (int i = 0; i < Model.Columns.Count; i++)
- {
- <th>@Model.Columns[i].ColumnName</th>
- }
- </tr>
- @for (int i = 0; i < Model.Rows.Count; i++)
- {
- <tr>
- @for (int j = 0; j < Model.Columns.Count; j++)
- {
- <td>@Model.Rows[i][j]</td>
- }
- </tr>
- }
- </table>
- }
- <div>
-
- </div>
- }
- </body>
- </html>
Let’s run the application and upload an Excel file.
Preview
Let’s upload an empty file or file other than Excel. Then, we will get the below messages on View.
Export Data to Excel with ClosedXML
Let’s add another action for demonstration, i.e., WriteDataToExcel() in HomeController. I have created a GetData method which will return some dummy data in the DataTable. I have mentioned the name of the Data Table which will be shown as the Excel worksheet name. In a real project, that might be coming from the Business Layer. Then, we are creating an XLWorkbook object and adding Data Table in the worksheet. After that, we are saving the file as a memory stream and returning the file to the user.
- public DataTable getData() {
-
- DataTable dt = new DataTable();
-
- dt.TableName = "EmployeeData";
-
- dt.Columns.Add("ID", typeof(int));
- dt.Columns.Add("Name", typeof(string));
- dt.Columns.Add("City", typeof(string));
-
- dt.Rows.Add(1, "Anoop Kumar Sharma", "Delhi");
- dt.Rows.Add(2, "Andrew", "U.P.");
- dt.AcceptChanges();
- return dt;
- }
-
- public ActionResult WriteDataToExcel()
- {
- DataTable dt = getData();
-
- string fileName = "Sample.xlsx";
- using (XLWorkbook wb = new XLWorkbook())
- {
-
- wb.Worksheets.Add(dt);
- using (MemoryStream stream = new MemoryStream())
- {
- wb.SaveAs(stream);
-
- return File(stream.ToArray(), "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet", fileName);
- }
- }
- }
Let’s run the application and hit the WriteDataToExcel action method. An Excel file named as Sample will be downloaded.
Thanks.