In software applications, sometime 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 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 it for the commercial project. For more details, click here to view the license on GitHub.
Import or Reading 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.
Import or Reading 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.
Get Action of Upload Excel Action will return a view as shown in 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:
Let’s run the application and upload an excel file.
Preview:
Let’s run the application and hit WriteDataToExcel action method. Excel file named as Sample will be downloaded.
Hope this will help you.
Thanks
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 cellused 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);
}
|
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>
|
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 a DataTable. I have mentioned the name of the datatable 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 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.
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 a DataTable. I have mentioned the name of the datatable 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 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() {
//Creating DataTable
DataTable dt =
new DataTable();
//Setiing 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);
}
}
}
|
Hope this will help you.
Thanks
[Download Source Code via Google Chrome]
I use ZetExcel for more than better result. just try it. Thanks
ReplyDeleteimporters data I think this is an informative post and it is very useful and knowledgeable. therefore, I would like to thank you for the efforts you have made in writing this article.
ReplyDeleteVery Useful and Helpful Article
ReplyDeleteThanks for the valuable comment!
Delete