How To Export Excel Using Closed.XML In MVC

Introduction

In this article, We will learn how to export excel using closed.xml in MVC.

In software applications, for sometimes a user needs to export or import the data in Excel format.

Install Package

ClosedXML.Excel

ClosedXML is used to create Excel files without the Excel application.

The typical example is for creating Excel reports on a web server.

Export Excel

Let’s begin

Creating a new MVC Project and install the ClosedXML.Excel library from Manage NuGet packages.

After the add new HomeController in your project and below code in it.

public ActionResult Index()
 {
     return View();
 }

 public ActionResult About()
 {
     ViewBag.Message = "Your application description page.";

     return View();
 }

 public ActionResult Contact()
 {
     ViewBag.Message = "Your contact page.";

     return View();
 }
 public ActionResult ExportExcel()
 {
     using (var workbook = new XLWorkbook())
     {
         //for new sheet
         var worksheet = workbook.AddWorksheet("Report");

         //set image on header
         var imagePath = Server.MapPath("~/Uploads/imagenadmin.jpg");//for image
         var image = worksheet.AddPicture(imagePath)
             .MoveTo(worksheet.Cell("A1"))
             .Scale(0.5);
         image.Width = 130;
         image.Height = 50;
         var imagerange = worksheet.Range("A1:B2");
         imagerange.Merge();

         //for header name
         worksheet.Cell("C1").Value = "Report";
         var range = worksheet.Range("C1:E2");
         range.Merge().Style.Font.SetBold().Font.FontSize = 14;
         worksheet.Range("C1:E2").Row(1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center;

         var currentRow = 3;
         worksheet.Cell(currentRow, 1).Value = "Offer #";
         worksheet.Cell(currentRow, 2).Value = "Offer Description";
         worksheet.Cell(currentRow, 3).Value = "Brand";
         worksheet.Cell(currentRow, 4).Value = "Media type";
         worksheet.Cell(currentRow, 5).Value = "Face Value";
         worksheet.Cell(currentRow, 6).Value = "Offer Type";
         worksheet.Cell(currentRow, 7).Value = "Dist. Date";
         worksheet.Cell(currentRow, 8).Value = "Exp. Date";
         worksheet.Cell(currentRow, 9).Value = "Total Dist. Quantity";

         //for add static data 
         for (int i = 0; i < 9; i++)
         {
             currentRow++;
             worksheet.Cell(currentRow, 1).SetValue(i + 1);
             worksheet.Cell(currentRow, 1).Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Right;//for right side value
             worksheet.Cell(currentRow, 2).SetValue(i + 1);
             worksheet.Cell(currentRow, 3).SetValue(i + 1);
             worksheet.Cell(currentRow, 4).SetValue(i + 1);
             worksheet.Cell(currentRow, 5).SetValue(i + 1);
             worksheet.Cell(currentRow, 6).SetValue(i + 1);
             worksheet.Cell(currentRow, 7).SetValue(i + 1);
             worksheet.Cell(currentRow, 8).SetValue(i + 1);
             worksheet.Cell(currentRow, 9).SetValue(i + 1);
         }
         // for column
         worksheet.Columns().AdjustToContents();
         var rango = worksheet.Range("A3:I3"); //Seleccionamos un rango
         rango.Style.Border.SetOutsideBorder(XLBorderStyleValues.Thick); //Generamos las lineas exteriores
         rango.Style.Border.SetOutsideBorderColor(XLColor.LightGray);
         rango.Style.Border.SetInsideBorder(XLBorderStyleValues.Medium);
         rango.Style.Border.SetInsideBorderColor(XLColor.LightGray);//Generamos las lineas interiores
         rango.Style.Alignment.Horizontal = XLAlignmentHorizontalValues.Center; //Alineamos horizontalmente
         rango.Style.Alignment.Vertical = XLAlignmentVerticalValues.Center;  //Alineamos verticalmente
         rango.Style.Font.FontSize = 12; //Indicamos el tamaño de la fuente
         rango.Style.Font.FontColor = XLColor.White;
         rango.Style.Fill.BackgroundColor = XLColor.FromHtml("#0F85BA"); //Indicamos el color
         using (var stream = new MemoryStream())
         {
             workbook.SaveAs(stream);
             var content = stream.ToArray();

             return File(
                 content,
                 "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet",
                 "Report.xlsx");
         }
     }
 }

and After Create view Index.cshtml and below code in it.

@{
    ViewBag.Title = "Home Page";
}

<div class="">
    <div class="col-md-12">
        <button type="button" class="btn btn-success mt-2" onclick="ExportExcel()">Export Excel</button>
    </div>
</div>

<script>
    function ExportExcel() {
        window.location.href = "/Home/ExportExcel";
    }
</script>

Let’s run the application and click to Export Excel button.

Output

Thank you for reading. If you have any doubt please let me know.

Read my previous blogs here.

Submit a Comment

Your email address will not be published.

Subscribe

Select Categories