我有一个动作
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 格式标头的字节数组