Export excel file using MVC and JQuery

public ActionResult Export(Data)
{
Datatable dtable=”” //logic of fetching all the records from database based on data sent from request
FileContentResult fobject;
using (XLWorkbook wb = new XLWorkbook())
{
wb.Worksheets.Add(dtable);
using (MemoryStream stream = new MemoryStream())
{
wb.SaveAs(stream);
var bytesdata = File(stream.ToArray(), “application/vnd.openxmlformats-officedocument.spreadsheetml.sheet”, “Report.xlsx”);
//Content type is used according to latest xlsx format
fobject = bytesdata;
}
}
return Json(fobject, JsonRequestBehavior.AllowGet); //returning bytes of file data as json object
}
$.ajax({
type: “POST”,
url: “@(Url.Action(“Export”,”Master”))” // method name, controller name
data: formData,
success: function (filedata) {
var bytes = new Uint8Array(filedata.FileContents);
var blob = new Blob([bytes], {type: “application/vnd.openxmlformats-officedocument.spreadsheetml.sheet” });
var link = document.createElement(‘a’);
link.href = window.URL.createObjectURL(blob);
link.download = “Report.xlsx”;
link.click();
},
error: function (err) {
}
cache: false,
contentType: false,
processData: false,
});
  1. Setting the MaxJsonLength property default value within your web.config
<configuration><system.web.extensions><scripting><webServices><jsonSerialization maxJsonLength=”68323055" /></webServices></scripting></system.web.extensions></configuration>
JsonResult result = Json(fobject);result.MaxJsonLength = 7895389;

--

--

--

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *

Love podcasts or audiobooks? Learn on the go with our new app.

Recommended from Medium

Javascript inheritance and object oriented programming

Component lifecycle in Blazor

flooks v4, auto optimize, update on demand. The simplest React Hooks state manager

Programming for Beginners: Understanding the DOM

Storing credentials the right way!

AMP Lightbox with Dynamic Data

100 days of code — day 17 & 18, core JS

Can Vue.js be the replacement for AngularJS?

Get the Medium app

A button that says 'Download on the App Store', and if clicked it will lead you to the iOS App store
A button that says 'Get it on, Google Play', and if clicked it will lead you to the Google Play store
Vaibhav Bhapkar

Vaibhav Bhapkar

Technical Speaker | Computer Engineer | Full Stack Web Developer | ML Enthusiast | * Knowledge Shared = Knowledge² *

More from Medium

Styling with Chrome Developer Tools!!

Creating a custom post type in a Wordpress Plugin

PHP master Object-Oriented Programming OOP

Abstract class vs interface