Skip to content

Instantly share code, notes, and snippets.

@lucasselliach
Last active March 11, 2016 17:17
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lucasselliach/a1b3e53289653b5f631d to your computer and use it in GitHub Desktop.
Save lucasselliach/a1b3e53289653b5f631d to your computer and use it in GitHub Desktop.
public class ExportToExcelService
{
public void ToExcel(HttpResponseBase Response, object clientsList)
{
var grid = new System.Web.UI.WebControls.GridView();
grid.DataSource = clientsList;
grid.DataBind();
Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
Response.ContentType = "application/excel";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();
}
}
<h3>Exporta dados para excell</h3>
@Html.ActionLink("Export to Excel", "Excel")
// GET: ClientResponse
[Authorize(Roles = "Admin")]
public void Excel()
{
var customClaim = Request.GetOwinContext().Authentication.User.Claims.First(c => c.Type == ClaimTypes.UserData).Value;
var userData = JsonConvert.DeserializeObject<LoginSerializeModel>(customClaim);
var authorization = userData.TokenType + " " + userData.AccessToken;
var estabsUsers = _ctx.Establishments.ToList();
var clients = _ctx.Users.ToList();
var clientsViewModel = new List<ClientViewModel>();
foreach (var c in clients)
{
var list = _ctx.Payments.Where(x => x.Owner_Id == c.Id);
var listMonth = _ctx.Payments.Where(x => x.Owner_Id == c.Id && x.Date.Month == DateTime.Now.Month);
clientsViewModel.Add(new ClientViewModel(
c.Name,
c.Email,
c.PhoneNumber,
list.Any() ? list.Sum(x => x.Value) : 0,
listMonth.Any() ? listMonth.Sum(x => x.Value) : 0
));
}
ExportToExcelService exportToExcelService = new ExportToExcelService();
exportToExcelService.ToExcel(Response, clientsViewModel);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment