I am trying to export all the users in my database to an excel file.
After running this code and debugging i run into no errors and the LetsExcelAll() method is being hit and run all the way through. Not sure what I am missing. When code is done running no errors are encountered and no download begins.
Controller:
public void LetsExcelAll()
{
try
{
var userRepo = new UsersRepository();
XLWorkbook wb = null;
wb = userRepo.DownloadUsers();
Response.Clear();
Response.Buffer = true;
Response.Charset = "";
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
Response.AddHeader("content-disposition", "attachment;filename=Users.xlsx");
using (MemoryStream MyMemoryStream = new MemoryStream())
{
wb.SaveAs(MyMemoryStream);
MyMemoryStream.WriteTo(Response.OutputStream);
Response.Flush();
Response.End();
}
}
catch(Exception ex)
{
throw ex;
}
}
REPO:
public XLWorkbook DownloadUsers()
{
try
{
if (thisConnection.State == ConnectionState.Closed)
thisConnection.Open();
MySqlCommand download = thisConnection.CreateCommand();
download.CommandText = UserQueries.DownloadUsers;
using (MySqlDataAdapter sda = new MySqlDataAdapter())
{
sda.SelectCommand = download;
using (DataTable dt = new DataTable())
{
sda.Fill(dt);
using (XLWorkbook wb = new XLWorkbook())
{
var ws = wb.Worksheets.Add(dt, "ALL_Users");
ws.Columns().AdjustToContents();
ws.Columns().Style.Alignment.SetWrapText();
return wb;
}
}
}
}
catch(Exception ex)
{
throw ex;
}
finally
{
thisConnection.Close();
}
}
VIEW: (HOW I CALL THE METHOD)
$("#downloadAllUsers").click(function () {
$.post("/Users/LetsExcelAll")
});