アクションがあります
public FileContentResult DownloadCSV()
{
var people = new List<Person> { new Person("Matt", "Abbott"), new Person("John","Smith") };
string csv = "Charlie, Chaplin, Chuckles";
Extensions.ToCSV(new DataTable());
return File(new System.Text.UTF8Encoding().GetBytes(csv), "text/csv", "Report123.csv");
}
とクラス
public static class Extensions
{
public static string ToCSV(DataTable table)
{
var result = new StringBuilder();
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(table.Columns[i].ColumnName);
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
foreach (DataRow row in table.Rows)
{
for (int i = 0; i < table.Columns.Count; i++)
{
result.Append(row[i].ToString());
result.Append(i == table.Columns.Count - 1 ? "\n" : ",");
}
}
return result.ToString();
}
}
new System.Text.UTF8Encoding().GetBytes(csv)
作成
string csv = "Charlie, Chaplin, Chuckles"
バイト配列に変換する方法
var people = new List<Person> { new Person("Matt", "Abbott"), new Person("John","Smith") };
csv のフォーマットされたヘッダーを持つバイト配列に