Note
Access to this page requires authorization. You can try signing in or changing directories.
Access to this page requires authorization. You can try changing directories.
Question
Monday, August 10, 2015 8:56 AM
How can i export a view in an MVC Application to MS Word Document retaining the view's Layout?
All replies (2)
Tuesday, August 11, 2015 7:22 AM ✅Answered
Hi Victor_Usoro,
In my option, the easiest way is to use the function in Word, steps as below:
Open Word file->Insert->Quick Parts->Filed, in the “Field Names”->Include Text-> enter the URL, and press OK. Then the web page will be inserted into Word file.
In another way, you could try to save the mvc view to word document, but it will show up the html tags. I think you could copy the html tags in the word file to text file, add the “<html>” and “</html>” to the header and footer, rename the textfile as .html, insert the .html into word document. For save the mvc view to word document, you could try the code below:
public ActionResult ExportToWord()
{
var list = new List<Item>();
list.Add(new Item { Id = 1 });
list.Add(new Item { Id = 2 });
list.Add(new Item { Id = 3 });
list.Add(new Item { Id = 4 });
string htmlString = this.RenderRazorViewToString(@"Index", list);
Response.AddHeader("Content-Disposition", "filename=EFFReport.doc");
Response.ContentType = "application/msword";
Response.Write(htmlString);
return null;
}
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);
viewResult.ViewEngine.ReleaseView(ControllerContext, viewResult.View);
return sw.GetStringBuilder().ToString();
}
}
You could refer the link below for more information.
#Render a view as a string
http://stackoverflow.com/questions/483091/render-a-view-as-a-string
#How to export a razor view to word in mvc3
http://stackoverflow.com/questions/14155680/how-to-export-a-razor-view-to-word-in-mvc3
Best Regards,
Tony
Monday, August 10, 2015 11:15 AM
http://www.codeproject.com/Articles/7341/Dynamically-generate-a-MS-Word-document-using-HTML