[英]for csv convert List<class> into byte array
我有一個動作
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();
}
}
新的System.Text.UTF8Encoding()。GetBytes(csv)
創造
string csv = "Charlie, Chaplin, Chuckles"
轉換為字節數組如何轉換
var people = new List<Person> { new Person("Matt", "Abbott"), new Person("John","Smith") };
到帶格式的CSV格式頭的字節數組
我不明白你想要什么。 但是根據我對您前面提到的問題的理解,以下是將對象轉換為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; }
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.