This is a simple example where we will discuss how we can download excel through ajax request. This example will use jquery and .net mvc and NPOI framework to create an Excel worksheet.
Below is the snippet where we are making an ajax call to an action method on controller on button click.
$(document).ready(function () {
$('.js-getExcel').on('click', function (e) {
e.preventDefault();
var $this = $(this);
if ($this.hasClass("processing")) {
console.log("Form submission in progress..");
return false;
}
$this.addClass("processing");
var $form = $this.closest('form');
var url = $form.attr("action");
$.getJSON(url, function (result) {
$this.removeClass("processing");
if (result && result.success) {
var arr = ['MyFileName_', getFormattedTime(), '.xls'];
var fileName = arr.join('');
var a = document.createElement("a");
a.href = "data:application/octet-stream;base64," + result.response;
a.download = fileName;
a.click();
} else {
$('.js-message').html(result.response).show().delay(8000).hide(400);
}
});
return false;
});
});
function getFormattedTime() {
var today = new Date();
var y = today.getFullYear();
var mo = today.getMonth() + 1;
var d = today.getDate();
var h = today.getHours();
var m = today.getMinutes();
var s = today.getSeconds();
return y + "-" + mo + "-" + d + "-" + h + "-" + m + "-" + s;
}
Below is the snippet of controller action.
public JsonResult ExportExcel(Model model)
{
List report = new List();
try
{
// populate report Object with data you want to write to excel
var workBook = WriteToExcel(report, "xls");
//Write the Workbook to a memory stream
MemoryStream output = new MemoryStream();
workBook.Write(output);
String file = Convert.ToBase64String(output.ToArray());
return Json(new { success = true, response = file }, JsonRequestBehavior.AllowGet);
}
catch (Exception ex)
{
return Json(new { success = false, response = ex.Message }, JsonRequestBehavior.AllowGet);
}
}
private IWorkbook WriteToExcel(List report, string extension)
{
IWorkbook workbook;
if (extension == "xls")
{
workbook = new HSSFWorkbook();
}
else
{
throw new Exception("This format is not supported");
}
ISheet sheet = workbook.CreateSheet("SheetName");
//make a header row
var headerRow = sheet.CreateRow(0);
headerRow.CreateCell(0).SetCellValue("Id");
headerRow.CreateCell(1).SetCellValue("Name");
//(Optional) freeze the header row so it is not scrolled
sheet.CreateFreezePane(0, 1, 0, 1);
int rowNumber = 1;
foreach (var item in report)
{
//Create a new Row
var row = sheet.CreateRow(rowNumber++);
//Set the Values for Cells
row.CreateCell(0).SetCellValue(item.Id);
row.CreateCell(1).SetCellValue(item.Name);
sheet.CreateRow(rowNumber++);
}
for (int i = 0; i < sheet.GetRow(0).PhysicalNumberOfCells; i += 1)
{
sheet.AutoSizeColumn(i);
}
return workbook;
}