sexta-feira, 27 de setembro de 2013

Very simple way to transform HTML into Excel - MVC3

Hi!

I was wondering about how to transform HTML into Excel format using Razor. I've been searching on the Internet and a came out with the solution showed on picture 1.

1 - Create a view called Report.cshtml

2 - In the controller I created two methods

        public string RenderRazorViewToString(string viewName, object model)
        {
            ViewData.Model = model;
            using (var sw = new StringWriter())
            {
                var viewResult = ViewEngines.Engines.FindPartialView(ControllerContext, viewName);
                var viewContext = new ViewContext(ControllerContext, viewResult.View, ViewData, TempData, sw);
                viewResult.View.Render(viewContext, sw);
                return sw.GetStringBuilder().ToString();
            }
        }


        public ActionResult TerritoriesInExcel(string searchString)
        {
            string lStrSearchString = searchString == null ? "" : searchString; ;
            var myTerritories = (new TerritoriesDAO()).getAll(1, true, lStrSearchString);
            Response.ClearContent();
            Response.AddHeader("content-disposition", "attachment;filename=myTerritories.xls");
            Response.ContentType = "application/excel";   

            Response.Write(RenderRazorViewToString("Report",myTerritories));
            Response.End();
            return View(myTerritories);

        }

3 - I have a Index.cshtml in the folder Views

So, the sequence is

Index -> Controller -> Change header response -> Transform Report.cshtml into a string -> make the call -> return to Index.cshtml.

 Two main points: The change that was made to the header of response and the transformation of the view into a string.

Notice that RenderRazorViewToString is a generic function and can be used in whatever context.


picture 1.

References
http://amitpatelit.com/2013/05/22/export-to-excel-in-asp-net-mvc/
http://akinyusufer.blogspot.in/2011/05/razor-render-mvc3-view-render-to-string.html

Nenhum comentário:

Postar um comentário