Export And Import Excel File Using ClosedXML In ASP.NET MVC

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 the 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.

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.

 ASP.NET MVC

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();
    // Checking file content length and Extension must be .xlsx
    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));
        // Saving the file
        file.SaveAs(path);
        // Started reading the Excel file.
        using (XLWorkbook workbook = new XLWorkbook(path))
        {
            IXLWorksheet worksheet = workbook.Worksheet(1);
            bool FirstRow = true;
            // Range for reading the cells based on the last cell used.
            string readRange = "1:1";
            foreach (IXLRow row in worksheet.RowsUsed())
            {
                // If Reading the First Row (used) then add them as column name
                if (FirstRow)
                {
                    // Checking the Last cell used for column generation in datatable
                    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
                {
                    // Adding a Row in datatable
                    dt.Rows.Add();
                    int cellIndex = 0;
                    // Updating the values of datatable
                    foreach (IXLCell cell in row.Cells(readRange))
                    {
                        dt.Rows[dt.Rows.Count - 1][cellIndex] = cell.Value.ToString();
                        cellIndex++;
                    }
                }
            }
            // If no data in Excel file
            if (FirstRow)
            {
                ViewBag.Message = "Empty Excel File!";
            }
        }
    }
    else
    {
        // If file extension of the uploaded file is different then .xlsx
        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 its 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.

Upload Excel Action

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

Preview

Let’s upload an empty file or file other than Excel. Then, we will get the below messages on View.

Messages

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 save the file as a memory stream and return the file to the user.

public DataTable getData()
{
    // Creating DataTable
    DataTable dt = new DataTable();
    // Setting Table Name
    dt.TableName = "EmployeeData";
    // Add Columns
    dt.Columns.Add("ID", typeof(int));
    dt.Columns.Add("Name", typeof(string));
    dt.Columns.Add("City", typeof(string));
    // Add Rows in DataTable
    dt.Rows.Add(1, "Anoop Kumar Sharma", "Delhi");
    dt.Rows.Add(2, "Andrew", "U.P.");
    dt.AcceptChanges();
    return dt;
}
// GET: Home
public ActionResult WriteDataToExcel()
{
    DataTable dt = getData();
    // Name of File
    string fileName = "Sample.xlsx";
    using (XLWorkbook wb = new XLWorkbook())
    {
        // Add DataTable in worksheet
        wb.Worksheets.Add(dt);
        using (MemoryStream stream = new MemoryStream())
        {
            wb.SaveAs(stream);
            // Return xlsx Excel File
            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 Sample will be downloaded.

 WriteDataToExcel

Hope this will help you.

Thanks.


Similar Articles