Tuesday, September 13, 2022

Save to Excel on Client side

Client-side code calling a server side endpoint.
utils.getExport = function () { window.location = urbase + '/Home/GetExportRowsRedir?tab=' + $('#tab').val() + "&query=" + $('#searchStar').val() + "&submitted=" + $('#filterProcessed').val(); };

Server-side endpoint building and returning a File to client side

[HttpGet]
public FileResult GetExportRowsRedir(int tab, string query, int submitted)
{
NavisionIntegrationEntities navIModel = new NavisionIntegrationEntities();
var rows = navIModel.usp_GetCustomerServiceOrderWeb2("", query, "", "", "", "", tab.ToString(),
submitted, 0, 100000, 0).ToList();
StringBuilder sb = new StringBuilder();
sb.AppendLine("Created,Last Name,First name,Address,Address 2,City,State,Zip,Country,SKU,Qty,Phone,Email,Ticket #,Procd,External_Tracking_No_,PNo_,ShippingNo_,Agent" +
(AdminUtils.IsAdmin(User.Identity.Name) ? ",User" : ""));
foreach (var row in rows)
{
sb.Append(row.Date_Created);
sb.Append(",");
sb.Append(row.Last_Name);
sb.Append(",");
sb.Append(row.First_Name);


if (AdminUtils.IsAdmin(User.Identity.Name))
{
sb.Append(",");
sb.Append(row.Created_by);
}

sb.AppendLine();
}

MemoryStream stream = new MemoryStream(System.Text.Encoding.UTF8.GetBytes(sb.ToString()));

return File(stream, "text/csv", string.Format("Export-{0}.csv", DateTime.Now.ToString("yyyyMMdd-HHmmss")));
}


Upon completion of the server side code and returning back to client, the file is dwonloaded to user's machine. For example in Chrome:

No comments: