0

我有一个动作

 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 格式标头的字节数组

4

1 回答 1

0

我不明白你想要什么。但是根据我对您之前提出的问题的理解,以下是将对象转换为字节 [] 的方法。

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; }
}
于 2012-10-08T12:44:20.803 回答