I need to export webgrid data into excel, I am using mvc 5 application. one button in view called Export, click that button, webgrid data into export into excel file. webgrid generated dynamic data, dont know how many columns or rows.
public ActionResult RunReports(int? id)
{
DomainContext CurrentLoginUser = ActiveDirectory_AccessModel.GetUserDetails(); // Username
var userDetails = (from c in db.SP_GR_Get_Userdetails(CurrentLoginUser.DisplayName)
select c.user_roles).FirstOrDefault();
if (userDetails == null)
{
return RedirectToAction("NoAccess");
}
var runResult = (from c in db.tbl_GR_Reports
where c.Report_ID == id
select c).SingleOrDefault();
DataSet ds = new DataSet();
DataTable dt = new DataTable();
if (runResult != null)
{
Microsoft.Practices.EnterpriseLibrary.Data.Database salesworldDbConn = new SqlDatabase(runResult.Db_Connection);
DbCommand cmd = salesworldDbConn.GetSqlStringCommand(runResult.Query);
try
{
ds = salesworldDbConn.ExecuteDataSet(cmd);
}
finally
{
cmd.Dispose();
salesworldDbConn = null;
}
if (ds != null && ds.Tables.Count > 0)
{
dt = ds.Tables[0];
}
}
return View(dt);
}