I followed this guide which was recommended in another post about this but I can't quite get it to work. I get a 404 error when trying to redirect to /LogModelsController/ExportData which - as I understood it - was what I was supposed to do.
_LogPartialLayout.cshtml
@using (Html.BeginForm("ExportData", "LogModelsController", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table class="table">
<tr>
<th>
@Html.ActionLink("message", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
@Html.ActionLink("timestamp", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter })
</th>
<th>
@Html.ActionLink("level", "Index", new { sortOrder = ViewBag.NameSortParm, currentFilter = ViewBag.CurrentFilter })
</th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.message)
</td>
<td>
@Html.DisplayFor(modelItem => item.timeStamp)
</td>
<td>
@Html.DisplayFor(modelItem => item.level)
</td>
</tr>
}
</table>
<input type="submit" name="Export" id="Export" value="Export" />
}
LogModelsController.cs
public ActionResult ExportData()
{
GridView gv = new GridView();
gv.DataSource = db.Log.ToList();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Loglist.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter sw = new StringWriter();
HtmlTextWriter htw = new HtmlTextWriter(sw);
gv.RenderControl(htw);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
return RedirectToAction("~/LogModels/Index");
}
LogModel.cs
namespace ASDMVC.Models
{
[Table("Log")]
public class LogModel
{
[Key]
public long id { get; set; }
public string message { get; set; }
public DateTime timeStamp { get; set; }
public string level { get; set; }
public int customerId { get; set; }
}
public class LogDBContext:DbContext
{
public LogDBContext() : base("MySqlConnection")
{
}
public DbSet <LogModel> Log { get; set; }
}
}
TD;DR: How do I properly export this table to Excel?
Bonus: Does it work with PagedList too?
Edit 3 - SOLVED
Index.cshtml:
@using (Html.BeginForm("ExportData", "LogModels"))
{
<input type="submit" name="Export" id="Export" value="Export" />
}
LogModelsController.cs
public ActionResult ExportData()
{
DataTable dataTable = GetData();
using (ExcelPackage package = new ExcelPackage())
{
var ws = package.Workbook.Worksheets.Add("My Sheet");
//true generates headers
ws.Cells["A1"].LoadFromDataTable(dataTable, true);
var stream = new MemoryStream();
package.SaveAs(stream);
string fileName = "myfilename.xlsx";
string contentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
stream.Position = 0;
return File(stream, contentType, fileName);
}
}
public DataTable GetData()
{
DataTable dt = new DataTable();
if (ModelState.IsValid)
{
using (SqlConnection conn = new SqlConnection(System.Configuration.ConfigurationManager.ConnectionStrings["MySqlConnection"].ConnectionString))
{
using (SqlCommand comm = conn.CreateCommand())
{
comm.Parameters.AddWithValue("@val1", Session["myID"]);
comm.CommandText = "SELECT * FROM dbo.Log WHERE CustomerId = @val1";
try
{
conn.Open();
dt.Load(comm.ExecuteReader());
}
catch (SqlException e)
{
throw new Exception(e.ToString());
}
}
}
}
return dt;
}
I made a mistake in the CommandText and put "Id" instead of "CustomerId" - it now returns the entire table in the Excel file.