for csv将List <class>转换为字节数组</class>

时间:2012-10-08 12:36:32

标签: c# asp.net-mvc-3 list csv

我有一个动作

 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

格式化标头的字节数组中

1 个答案:

答案 0 :(得分:0)

我不明白你想要什么。但根据我对你之前提到的问题的理解,将对象转换为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; }
}
相关问题