mvc导出excel文件可以使用文件流的方式导出:
后台实现:
/// <summary>
/// 导出开工条件验收清单
/// </summary>
/// <param name="projectId"></param>
/// <returns></returns>
public ActionResult ExportToExcel(Guid? nodeId, int? nodeType)
{
string MCDateTimePic = null;
//string EngineerTypeNameDrop = null;
//string tbDangerName = null;
//string ProgressStatusDrop = null;
//string monitorLeveIds = null;
DateTime searchTime = Convert.ToDateTime(ReadCache("searchTime")).AddMonths(-1);
if (!string.IsNullOrEmpty(MCDateTimePic))
{
searchTime = Convert.ToDateTime(MCDateTimePic).AddMonths(-1);
}
var list = serviceImDanOvSearch.GetImportDanOverallSearchListByParam(searchTime, nodeId.Value, nodeType.Value);
var str = RenderPartialViewToString(this, "ExportTemplate/OverallSearchListExportTemplate", list);
return File(Encoding.UTF8.GetBytes(str), "application/octet-stream", "开工验收清单" + DateTime.Now.ToString("yyyyMMdd") + ".xls");
/File方法为mvc5.0自带方法,表示放回一个fileContentResult文件流对象。
}
//对象转换为数据流
public string RenderPartialViewToString(Controller controller, string viewName, object model)
{
controller.ViewData.Model = model;
try
{
using (StringWriter sw = new StringWriter())
{
ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(controller.ControllerContext, viewName);
ViewContext viewContext = new ViewContext(controller.ControllerContext, viewResult.View, controller.ViewData, controller.TempData, sw);
viewResult.View.Render(viewContext, sw); return sw.GetStringBuilder().ToString();
}
}
catch (Exception ex)
{
return ex.ToString();
}
}
前台页面代码:
@model List<RTSafe.ZTSD.BusinessModules.DanModules.Models.DynamicManagerModel>
<h2>重要危险源综合清单</h2>
<table border="1">
<thead>
<tr>
<th>序号</th>
<th>列名1</th>
<th>列名2</th>
</tr>
@{
var i = 1;
}
@foreach (var item in Model)
{
<tr>
<td>@i</td>
<td align="center">@item.ProjectName</td>
<td align="center">@item.DangerNameAndAccidentName</td>
<td align="center">@item.Province</td>
<td align="center">@item.Name</td>
</tr>
i = i + 1;
}
</thead>
<tr></tr>
</table>