Skip to content

Instantly share code, notes, and snippets.

@mahizsas
Forked from wullemsb/HomeController.cs
Created August 27, 2014 22:44
Show Gist options
  • Select an option

  • Save mahizsas/d96823c159fe4412b97d to your computer and use it in GitHub Desktop.

Select an option

Save mahizsas/d96823c159fe4412b97d to your computer and use it in GitHub Desktop.
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Web;
using System.Web.Mvc;
namespace SampleApp.Controllers
{
public class HomeController : Controller
{
public ActionResult Index()
{
return View();
}
public ActionResult DownloadExcel()
{
var tableData = new StringBuilder();
var products = GetProducts();
foreach(var product in products)
{
tableData.Append("<Row ss:AutoFitHeight='0'>");
tableData.Append("<Cell><Data ss:Type='String'>" + product.ProductName + "</Data></Cell>");
tableData.Append("<Cell><Data ss:Type='Number'>" + product.UnitPrice + "</Data></Cell>");
tableData.Append("</Row>");
}
// read the excel file template from the resource
var xmlTemplate=System.IO.File.ReadAllText(Server.MapPath("~/App_Data/ExcelTemplate.xml"));
//Replace placeholder content
xmlTemplate = xmlTemplate.Replace("$ROWSPLACEHOLDER$", tableData.ToString());
var data=System.Text.Encoding.UTF8.GetBytes(xmlTemplate);
return File(data,"application/vnd.ms-excel", "Products.xml");
}
private IEnumerable<Product> GetProducts()
{
using (var ctx = new NorthwindEntities())
{
return ctx.Products.ToList();
}
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment