Tag Archives: asp.net mvc

How to use ASP.NET MVC with OfficeWriter

Problem

A number of customers have asked about support for ASP.NET MVC. With the introduction of ASP.NET MVC, the method to send OfficeWriter-generated files to the user requires a few more lines of code. In ASP.NET WebForms, OfficeWriter can write directly to the HttpResponse stream via the Save method, allowing for a one-line implementation. In MVC, all the functions from a Controller return an ActionResult, and it requires a different approach to return the file to the user.

Solution

To facilitate file downloads, we need an ActionResult to return the file generated by OfficeWriter. For use in ASP.NET MVC, we need to return our file via an ActionResult for the Controller’s action; the specific type used below for doing that is the FileStreamResult by using OfficeWriter to get a stream of the file.

The overview of what we need to do is summarized in the algorithm below:

  1. Create the appropriate OfficeWriter object.
  2. Get the data into the file, using the various data binding methods like ExcelTemplate.BindData and WordTemplate.SetDataSource.
  3. Process the file.
  4. Save the file to an in-memory Stream (using MemoryStream); check out ExcelTemplate.SaveExcelApplication.SaveWordTemplate.Save, and WordApplication.Save.
  5. Return the FileStreamResult, set to use the in-memory Stream.

The following is a C# sample that uses ExcelTemplate. This general approach also works for ExcelApplication, WordTemplate, and WordApplication.

public ActionResult Download()
{
if (ModelState.IsValid)
{
var excelTemplate = new ExcelTemplate();
excelTemplate.Open(Server.MapPath("~/Templates/Download_Template.xlsx"));


// get the data into the file
excelTemplate.Process();
var stream = new MemoryStream();
excelTemplate.Save(stream);


// make sure to reset the position because we will be reading it again
stream.Position = 0;
var actionResult = new FileStreamResult( stream, "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" );
actionResult.FileDownloadName = "Download.xlsx"; return actionResult;
} return View();
}

The above code would be placed inside a Controller for the Download action. When this action is activated, a file download prompt will appear for the user with the file name that was given to the FileStreamResult.