About how to export excel using mvc and excel using mvc
You can use the file stream method to export excel files by using mvc:
Background implementation:
/// <Summary>
/// Export the acceptance list of the Start Condition
/// </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. getimpdandanoverallsearchlistbyparam (searchTime, nodeId. Value, nodeType. Value );
Var str =RenderPartialViewToString (this, "ExportTemplate/OverallSearchListExportTemplate", list );
Return File (Encoding. UTF8.GetBytes (str), "application/octet-stream", "Construction Acceptance List" + DateTime. now. toString ("yyyyMMdd") + ". xls ");
//// The File method is the built-in mvc5.0 method, indicating that a fileContentResult File stream object is put back.
}
// Convert an object to a data stream
Public string RenderPartialViewToString (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 ();
}
}
Front-end Page code:
@ Model List <RTSafe. ZTSD. BusinessModules. DanModules. Models. DynamicManagerModel>
<H2> comprehensive list of important hazard sources <Table border = "1">
<Thead>
<Tr>
<Th> serial number </th>
<Th> column name 1 </th>
<Th> column name 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>