Skip to content

Instantly share code, notes, and snippets.

@m-kulesza
Last active November 6, 2017 13:08
Show Gist options
  • Save m-kulesza/569450ee1750c6e169e4fb1975df5b13 to your computer and use it in GitHub Desktop.
Save m-kulesza/569450ee1750c6e169e4fb1975df5b13 to your computer and use it in GitHub Desktop.
asp.net ajax post + download file
public ActionResult GenerateXLS(string headersJSON, string rowsJSON)
{
JavaScriptSerializer srl = new JavaScriptSerializer();
var headers = srl.Deserialize<List<object>>(headersJSON);
var rows = srl.Deserialize<List<object[]>>(rowsJSON);
var sheet = _excelCreator.AddSheet("Test");
_excelCreator.CreateHeaders(sheet, headers);
_excelCreator.SetColumnsWidth(sheet);
foreach (var row in rows)
{
_excelCreator.AddRow(sheet, row);
}
var output = _excelCreator.CreateXLS()?.ToArray();
var fileName = "TestXLS_" + DateTime.UtcNow.ToString("yyy-MM-dd") + ".xls";
var response = System.Web.HttpContext.Current.Response;
response.ContentType = "application/vnd.ms-excel";
response.AddHeader("Content-Disposition", "attachment; filename=\"" + fileName + "\"");
if (output.Length > 0)
{
response.OutputStream.Write(output, 0, output.Length);
}
response.Flush();
response.SuppressContent = true;
return null;
}
function XLS() {
var action = "GenerateXLS";
var method = "POST";
var headers = [];
var rows = [];
$("th").each(function() {
headers.push(this.innerText);
});
$("tr").each(function() {
var data = [];
$(this).children("td").each(function() {
data.push(this.innerText);
});
if (data.length > 0) {
rows.push(data);
}
});
downloadFile(action, method, { "headersJSON": JSON.stringify(headers), "rowsJSON": JSON.stringify(rows) });
}
function downloadFile(action, method, input) {
"use strict";
var form;
form = $('<form />', {
action: action,
method: method,
style: 'display: none;'
});
if (typeof input !== 'undefined') {
$.each(input, function (name, value) {
$('<input />', {
type: 'hidden',
name: name,
value: value
}).appendTo(form);
});
}
form.appendTo('body').submit();
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment