export to excel through mvc3

可紊 提交于 2019-12-03 22:14:14

Instead of generating columns and headers of table in code bind,create a View for it so that you can easily add in-line styles to header and columns.

Add New class in

public class DownloadFileActionResult : ActionResult
    {
        public string ExcelGridView { get; set; }
        public string fileName { get; set; }

        public DownloadFileActionResult(string gv, string pFileName)
        {
            ExcelGridView = gv;
            fileName = pFileName;

        }


        public override void ExecuteResult(ControllerContext context)
        {

            //Create a response stream to create and write the Excel file
            HttpContext curContext = HttpContext.Current;
            curContext.Response.Clear();
            curContext.Response.AddHeader("content-disposition", "attachment;filename=" + fileName);
            curContext.Response.Charset = "";
            curContext.Response.Cache.SetCacheability(HttpCacheability.NoCache);
            curContext.Response.ContentType = "application/ms-excel";

            //Open a memory stream that you can use to write back to the response
            byte[] byteArray = Encoding.ASCII.GetBytes(ExcelGridView);
            MemoryStream s = new MemoryStream(byteArray);
            StreamReader sr = new StreamReader(s, Encoding.Unicode);

            //Write the stream back to the response
            curContext.Response.ContentEncoding = System.Text.Encoding.Unicode;
            curContext.Response.Write(sr.ReadToEnd());
            curContext.Response.End();




        }
    }  

which is inherit from ActionResult which is accept two parameter one is your View in string formatte and another is Excel-filename.

//In Controller 

public ActionResult SaveExcel()
{
            string html = RenderPartialViewToString("PartailViewName", model);
            // if your view don't have any model then you can pass as null

            html = html.Replace("\n", "");
            html = html.Replace("\r", "");
            html = html.Replace("  ", "");

            return new DownloadFileActionResult(html, "ExcelSheetName.xls");
}



      protected string RenderPartialViewToString(string viewName, object model)
            {
                if (string.IsNullOrEmpty(viewName))
                    viewName = ControllerContext.RouteData.GetRequiredString("action");

                ViewData.Model = model;

                using (StringWriter sw = new StringWriter())
                {
                    ViewEngineResult viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                    ViewContext viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                    viewResult.View.Render(viewContext, sw);
                    return sw.GetStringBuilder().ToString();


         }
    }

return type of PartialView is MvcHtmlString you can get it in controller, so i have return one method RenderPartialViewToString which accept two parameter one is PartailView and another is Model and it will return you RenderHtmlString of partial view.

create a partial view

//PartailViewName.cshtml

<table>
     <tr>
        <th style="background-color:Gray;">
            Column1
        </th>
       <th style="background-color:Gray;">
            Column1
        </th>
     </tr>
     <tr>
        <td>
             Coulmn data
        </td>
        <td>
            Coulmn data
        </td>
     </tr>
</table> 

NOTE : view must be partial view 2) your all data must be arrange in table structure only 3) give only in-line styles.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!