I have a Action
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");
}
and a class
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)
create
string csv = "Charlie, Chaplin, Chuckles"
into byte array how to convert
var people = new List<Person> { new Person("Matt", "Abbott"), new Person("John","Smith") };
into byte array with formatted header for csv
I do not understand what do you want. But based on my understanding of your question asked earlier following is the way to convert an object to byte[].
static void Main(string[] args)
{
Person p1 = new Person();
p1.ID = 1;
p1.Name = "Test";
byte[] bytes = ObjectToByteArray(p1);
}
private byte[] ObjectToByteArray(Object obj)
{
if(obj == null)
return null;
BinaryFormatter bf = new BinaryFormatter();
MemoryStream ms = new MemoryStream();
bf.Serialize(ms, obj);
return ms.ToArray();
}
[Serializable]
public class Person
{
public int ID { get; set; }
public string Name { get; set; }
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.