Wednesday, February 3, 2016

ASP.NET MVC: Creating and downloading MS Excel File

 #region Controller Action
public ActionResult Index()
{
// Download link displayed on this view
//<h2>@Html.ActionLink("Download", "Download")</h2>
return View();
}


public ActionResult Download()
{
var data = new List<DataRow>
{
new DataRow{Date = DateTime.Now, Amount = 1M, Note = "Good, one"},
new DataRow{Date = DateTime.Now, Amount = 2M}
};

string reportName = "SampleReport_" + DateTime.Now.ToString();
string reportNameCleansed = RemoveInvalidChars(reportName);
return File(Encoding.UTF8.GetBytes(GetCSVReportData(data)),
"application/text", reportNameCleansed + ".csv");
}
#endregion


#region Helpers
class DataRow
{
public DateTime Date { get; set; }
public Decimal Amount { get; set; }
public string Note { get; set; }
}


string RemoveInvalidChars(string fileName)
{
string ret = string.Empty;

foreach (char c in System.IO.Path.GetInvalidFileNameChars())
{
ret = fileName.Replace(c, '-');
}
return ret;
}


string GetCSVReportData(List<DataRow> data)
{
var fileData = new StringBuilder();
fileData.AppendLine("Date,Amount,Note");
foreach (var item in data)
  {
fileData.AppendFormat("{0},{1},\"{2}\"",
item.Date.ToString("yyyy-MM-dd"),
item.Amount.ToString("########0.0000"),
item.Note);
fileData.AppendLine();
}
return fileData.ToString();
}
#endregion