我有以下控制器。当我搜索特定年级时,我会得到一个列表。我想要的是将此结果导出为excel。我的导出按钮工作正常。但唯一的一点是,当我点击它时,它会尝试将db中的所有内容导出为excel。我想要的只是导出结果。任何的想法?
public ActionResult Index(string searchBy, string search)
{
if (!String.IsNullOrEmpty(searchBy) && !String.IsNullOrEmpty(search))
{
if (searchBy == "ID")
{
return View(db.students.Where(x => x.id==search).ToList());
}
else if (searchBy == "grade")
{
return View(db.students.Where(x => x.grade == search).ToList());
}
else
{
return View(db.students.Take(0));
}
}
public ActionResult ExportData()
{
GridView gv = new GridView();
gv.DataSource = db.students.ToList();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=students.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("Home");
}
这是我的索引视图中的一部分:
@using (Html.BeginForm("ExportData", "Home", FormMethod.Post, new { enctype = "multipart/form-data" }))
{
<table>
<tr>
<td></td>
<td>
<input type="submit" name="Export" id="Export" value="Export" />
</td>
</tr>
</table>
}
答案 0 :(得分:1)
您的ExportData()
操作只是检索db.students
的每个结果,它不知道您的视图中的内容。
假设您的学生列表包含您想要的所有数据,您可以将整个列表发布到您的操作中,例如:
public ActionResult ExportData(List<Student> students)
{
GridView gv = new GridView();
gv.DataSource = students;
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=students.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("Home");
}
或者您可以传递搜索参数并相应地过滤数据库,例如
public ActionResult ExportData(string searchBy, string search)
{
GridView gv = new GridView();
if (!String.IsNullOrEmpty(searchBy) && !String.IsNullOrEmpty(search))
{
if (searchBy == "ID")
{
gv.DataSource = db.students.Where(x => x.id==search).ToList();
}
else if (searchBy == "grade")
{
gv.DataSource = db.students.Where(x => x.grade == search).ToList();
}
}
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=students.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("Home");
}
不要忘记从您的观点发布必要的数据。