我正在控制器中使用导出方法,使用此方法将表中的数据下载到excel文件中: 这是索引文件中的表:
<table class="table">
<tr>
<th>
@Html.DisplayNameFor(model => model.Name)
</th>
<th>
@Html.DisplayNameFor(model => model.Marks)
</th>
<th>
@Html.DisplayNameFor(model => model.Grade)
</th>
<th></th>
</tr>
@foreach (var item in Model) {
<tr>
<td>
@Html.DisplayFor(modelItem => item.Name)
</td>
<td>
@Html.DisplayFor(modelItem => item.Marks)
</td>
<td>
@Html.DisplayFor(modelItem => item.Grade)
</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 ExportData()
{
GridView gv = new GridView();
gv.DataSource = db.Studentrecords.ToList();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=Marklist.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("StudentDetails");
}
一切正常,该表很容易下载到excel文件中,但是当我打开文件时,它在打开文件的开头给出了以下错误: 文件格式不匹配。文件可能已损坏或不安全。 问题的原因主要是因为文件以xls格式保存,而我想将其保存为xlxs格式,那怎么可能呢?
答案 0 :(得分:0)
要将MVC视图数据导出到Excel文件中,我正在使用ClosedXml库。
public ActionResult ExportToExcel()
{
var gv = new GridView();
gv.DataSource = this.GetEmployeeList();
gv.DataBind();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment; filename=DemoExcel.xls");
Response.ContentType = "application/ms-excel";
Response.Charset = "";
StringWriter objStringWriter = new StringWriter();
HtmlTextWriter objHtmlTextWriter = new HtmlTextWriter(objStringWriter);
gv.RenderControl(objHtmlTextWriter);
Response.Output.Write(objStringWriter.ToString());
Response.Flush();
Response.End();
return View("Index");
}
链接到完整文章Article Link