将.csv数据导入类

时间:2014-03-19 15:15:19

标签: c#

我有一些代码可以将类中的数据保存到.csv文件中,但是我不知道如何将它读回到类中,所以我可以将它放在listview中。以下是保存的代码:

        SaveFileDialog save = new SaveFileDialog();
        save.Filter = "Excel|*.csv";

        if (save.ShowDialog() == DialogResult.OK)
        {
            StreamWriter sw = new StreamWriter(save.FileName);
            try
            {
                sw.WriteLine("Name" + ";" + "Authors" + ";" + "Pages" + ";" + "Date" + ";" + "Price" + ";" + "Copies");
                foreach (Book b in bookList)
                {
                    string aux = "";
                    aux = string.Join(";", b.Authors);//I know I will probably need to change ';' here because it will have trouble reading it
                    sw.WriteLine(b.Name + ";" + aux + ";" + b.Pages + ";" + b.Date.ToString("dd.MM.yyyy") + ";" + b.Price + ";" + b.Copies);
                }
            }
            catch (IOException ert)
            {
                MessageBox.Show(ert.Message);
            }
            catch (Exception ew)
            {
                MessageBox.Show(ew.Message);
            }
            finally
            {
                sw.Close();
            }
        }

2 个答案:

答案 0 :(得分:1)

这实际上非常简单。假设您有以下课程Book

public class Book
{
    public string Name { get; set; }
    public int Pages { get; set; }
    public string AuthorName { get; set; }
}

然后你可以像这样简单地阅读:

var BooksFromCsv = from row in File.ReadLines(@"C:\books.csv").Where(arg => !string.IsNullOrWhiteSpace(arg) && arg.Length > 0).AsEnumerable()
                   let column = row.Split(';')
                   select new Book
                   {
                      Name = column[0],
                      Pages = column[1],
                      AuthorName = column[2],
                   };

结果将是IEnumerable<Book>。如果您想要列表或数组,只需附加.ToList().ToArray()

答案 1 :(得分:0)

如果您只想保存持久数据,可以像这样对序列进行序列化和反序列化:

//保存

using (var fs = new FileStream(path, FileMode.Create))
{
      var xSer = new XmlSerializer(typeof(objecttype));
      xSer.Serialize(fs, myObject);
}

// LOAD

using (var fs = new FileStream(path, FileMode.Open))
{
     var xSer = new XmlSerializer(typeof(objecttype));
     myObject = (objecttype)xSer.Deserialize(fs);
}