简体   繁体   English

将 .csv 文件读入 WPF 应用程序 (C#)

[英]Reading a .csv file into WPF application (C#)

I've just recently made a C# console application that could read a .csv file and write it to the console in a neat manner, however now I want to make it in WPF to make it even more neat.我最近刚刚制作了一个 C# 控制台应用程序,它可以读取 .csv 文件并将其以简洁的方式写入控制台,但是现在我想在 WPF 中使其更加简洁。

My previous console application looks like this:我以前的控制台应用程序如下所示:

class Program
{
    static void Main(string[] args)
    {
        string[] tokens;
        char[] separators = { ';' };
        string str = "";

        FileStream fs = new FileStream(@"D:\Dokumenter\Skole\6. semester\GUI\Exercises\Exercise2\02 deltagerliste.csv", 
                                       FileMode.Open);
        StreamReader sr = new StreamReader(fs, Encoding.Default);

        while ((str = sr.ReadLine()) != null)
        {
            tokens = str.Split(separators, StringSplitOptions.RemoveEmptyEntries);

            Console.WriteLine(String.Format("{0,-20}", tokens[0]) +
                              String.Format("{0,-15}", tokens[1]) +
                              String.Format("{0,-15}", tokens[2]) +
                              String.Format("{0,-15}", tokens[3]));
        }

        Console.ReadLine();            
    }
}

It works great, but I must admit that I have difficulties finding out where to begin with the WPF application.它工作得很好,但我必须承认我很难找到从哪里开始使用 WPF 应用程序。

So far I have conjured up the following XAML code with the four headers of the .csv file (since it has four columns) and I assume I have to find a way to put the appropriate rows into the respective columns.到目前为止,我已经用 .csv 文件的四个标题(因为它有四列)想出了以下 XAML 代码,我假设我必须找到一种方法将适当的行放入相应的列中。

<Window x:Class="WpfApplication1.MainWindow"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Deltagerliste" Height="350" Width="525" WindowStartupLocation="CenterScreen" WindowState="Maximized"
    Background="DeepPink"
    >
<ListView HorizontalAlignment="Left" Height="320" VerticalAlignment="Top" Width="517">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="First name"/>
            <GridViewColumn Header="Last name"/>
            <GridViewColumn Header="ID"/>
            <GridViewColumn Header="Email"/>
        </GridView>
    </ListView.View>
</ListView>

My main and initial problem is how I read in the file to the ListView.我的主要和最初的问题是我如何将文件读入 ListView。 I'm new to both C# and XAML and even though I'm well aware of how to open and read a file in C#, the syntax in XAML is a little confusing to me.我是 C# 和 XAML 的新手,尽管我很清楚如何在 C# 中打开和读取文件,但 XAML 中的语法对我来说有点混乱。

First: Create a class that will hold the data per row.第一:创建一个类来保存每行的数据。

public class Person
{
    public string FirstName { get; set; }
    public string LastName { get; set; }
    public int ID { get; set; }
    public string Email { get; set; }

    public Person(string firstName, string lastName, int id, string email)
    {
        FirstName = firstName;
        LastName = lastName;
        ID = id;
        Email = email;
    }
}

Then create a function that will return a list of Persons from the CSV file:然后创建一个函数,该函数将从 CSV 文件中返回人员列表:

public IEnumerable<Person> ReadCSV(string fileName)
{
    // We change file extension here to make sure it's a .csv file.
    // TODO: Error checking.
    string[] lines = File.ReadAllLines(System.IO.Path.ChangeExtension(fileName, ".csv"));

    // lines.Select allows me to project each line as a Person. 
    // This will give me an IEnumerable<Person> back.
    return lines.Select(line =>
    {
        string[] data = line.Split(';');
        // We return a person with the data in order.
        return new Person(data[0], data[1], Convert.ToInt32(data[2]), data[3]);
    });
}

Then configure your listview columns with the appropriate binding.然后使用适当的绑定配置您的列表视图列。 Note that the x:Name property is the name you will use to access this listview in the .cs file of the form:请注意, x:Name 属性是您将用于访问表单的 .cs 文件中的此列表视图的名称:

<ListView x:Name="ListViewPeople">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="First name" Width="100" DisplayMemberBinding="{Binding Path=FirstName}"/>
            <GridViewColumn Header="Last name" Width="150" DisplayMemberBinding="{Binding Path=LastName}"/>
            <GridViewColumn Header="ID" Width="40" DisplayMemberBinding="{Binding Path=ID}"/>
            <GridViewColumn Header="Email" Width="200" DisplayMemberBinding="{Binding Path=Email}"/>
        </GridView>
    </ListView.View>
</ListView>

Lastly you bind the ItemsSource of the listview to the method returning the Person list:最后,您将列表视图的 ItemsSource 绑定到返回 Person 列表的方法:

public MainWindow()
{
    InitializeComponent();

    // We can access ListViewPeople here because that's the Name of our list
    // using the x:Name property in the designer.
    ListViewPeople.ItemsSource = ReadCSV("example");
}

CSV File CSV文件

Henk;van Dam;1;henk.van.dam@gmail.com
Alex;the Great;2;alex.the_great@live.nl

End result最终结果

程序结果

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM