我无法将过滤的结果导出到Excel文件。我只是在学习ASP.Net和MVC。
我已经看过这里的建议,但是我无法使它生效。我不太确定如何使用另一个链接中提到的EditorTemplate 。
当前,当我导出时,所有数据都将导出,而与过滤器无关。如何不使用Web表单将视图上显示的内容导出到Excel文件?
谢谢..
这是我的观点,Index.cshtml:
@model IEnumerable<ExportToExcel.Models.Student>
@{
ViewBag.Title = "Index";
}
<h2>Index</h2>
<p>
@Html.ActionLink("Create New", "Create")
@using (Html.BeginForm("Index","Student",FormMethod.Get))
{
<p>
Name: @Html.TextBox("NameSearch")
<input type="submit" value="Search" />
@Html.ActionLink("Export to Excel","ExportToExcel")
</p>
}
</p>
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Age)
</th>
<th>
@Html.DisplayNameFor(model => model.Marks)
</th>
<th></th>
</tr>
@foreach (var item in Model)
{
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Age)
</td>
<td>
@Html.DisplayFor(modelItem => item.Marks)
</td>
<td>
@Html.ActionLink("Edit", "Edit", new { id = item.ID }) |
@Html.ActionLink("Details", "Details", new { id = item.ID }) |
@Html.ActionLink("Delete", "Delete", new { id = item.ID })
</td>
</tr>
}
</table>
在控制器中,我实现了以下内容:
public ActionResult Index(string nameSearch)
{
var students = from m in db.Students
select m;
if (!String.IsNullOrEmpty(nameSearch))
{
students = students.Where(n => n.Name.Contains(nameSearch));
}
return View(students);
}
public ActionResult ExportToExcel()
{
GridView gv = new GridView();
//if (!String.IsNullOrEmpty(nameSearch))
//{
// gv.DataSource = db.Students.Where(n => n.Name.Contains(nameSearch)).ToList();
//}
//else
//{
// gv.DataSource = db.Students.ToList();
//}
gv.DataSource = db.Students.ToList();
gv.DataBind();
Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/ms-excel";
Response.AddHeader("content-disposition", "attachment;filename=StudentList.xls");
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("Index");
}
好的,设法找到了答案。原始链接。
基本上,将搜索结果存储在会话中。然后,在导出过程中从会话中检索列表。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句