Trabla: C# & ASP.NET MVC : create and download csv example
Solving:
....
namespace MyApp.Controllers
{
public class ReportController: Controller
{
public ActionResult DownloadCSV()
{
var lvData = GetReportData();
// Create string with csv data
string lvCSV = GetCSV( lvData );
var lvFileName = string.Format(
"report_{0}.csv",
DateTime.Now.ToString("yyyy/MM/dd")
);
return File(
System.Text.Encoding.UTF8.GetBytes(lvCSV),
"text/csv" ,
lvFileName
);
}
// List of Dictionaries with data
public static IEnumerator<Dictionary<string,string>> GetReportData()
{
List<Dictionary<string,string>> lvData = new List<Dictionary<string,string>>();
Dictionary<string, string> lvRow = new Dictionary<string, string>();
lvRow.Add( "Name", "Alex" );
lvRow.Add( "Age", "29" );
lvData.Add( lvRow );
lvRow = new Dictionary<string, string>();
lvRow.Add( "Name", "John" );
lvRow.Add( "Age", "30" );
lvData.Add( lvRow );
return lvDat;
}
// Converst List of Dictionaries into string for csv file
public static string GetCSV( IEnumerator<Dictionary<string,string>> data )
{
string lvDelimiter = ",";
StringBuilder lvCSV = new StringBuilder();
// Headers
var lvTotalElements = rows.First().Count();
var lvIndex = 0;
foreach ( var lvItemKey in rows.First().Keys)
{
lvCSV.Append(lvItemKey);
if (lvIndex < lvTotalElements - 1) lvCSV.Append(lvDelimiter);
lvIndex++;
}
lvCSV.Append("\n");
// Data Rows
foreach( var lvRow in rows)
{
lvTotalElements = lvRow.Count();
lvIndex = 0;
foreach( var lvItemValue in lvRow.Values)
{
lvCSV.Append(lvItemValue);
if(lvIndex < lvTotalElements - 1) lvCSV.Append(lvDelimiter);
lvIndex++;
}
lvCSV.Append("\n");
}
return lvCSV.ToString();
}
}
}
No comments:
Post a Comment