【问题标题】:for csv convert List<class> into byte array对于 csv 将 List<class> 转换为字节数组
【发布时间】:2012-10-08 12:36:31
【问题描述】:

我有一个动作

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

【问题讨论】:

  • 鉴于您没有显示成员Person 有什么,这有点不可能......还有;如果我们包含转义值、多行值等,CSV 是不平凡的
  • 不清楚你在问什么。您是否只是想遍历people 并构建一个字符串以存储在 CSV 中?你想在那个字符串中做什么?
  • 我想要一种方法以格式化的方式转换 csv 中的列表值

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


【解决方案1】:

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

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; }
}

【讨论】:

  • bf.Serialize(ms, obj);显示错误“未标记为可序列化”
  • 您需要在您的类中添加 [Serializable] 属性以启用序列化。
猜你喜欢
  • 2020-03-23
  • 2011-05-13
  • 1970-01-01
  • 1970-01-01
  • 2021-08-05
  • 1970-01-01
  • 2019-09-02
  • 2019-06-05
  • 1970-01-01
相关资源
最近更新 更多