C# 如何在WPF MVVM应用程序中将ListView项导出到excel

C# 如何在WPF MVVM应用程序中将ListView项导出到excel,c#,wpf,listview,mvvm,C#,Wpf,Listview,Mvvm,我正在列表视图中获取数据,我想将这些数据导出到WPF MVVM中的Excel中。我是新来的,有人可以建议我的方法或建议的代码片段或编辑。这真的很有帮助 我提到了一些链接,但它们使用了WPF中无法使用的数据网格 Main Window.xaml <Window x:Class="MVVMDemo.UserRegistrationView" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xml

我正在列表视图中获取数据,我想将这些数据导出到WPF MVVM中的Excel中。我是新来的,有人可以建议我的方法或建议的代码片段或编辑。这真的很有帮助

我提到了一些链接,但它们使用了WPF中无法使用的数据网格

Main Window.xaml

<Window x:Class="MVVMDemo.UserRegistrationView"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006"
xmlns:d="http://schemas.microsoft.com/expression/blend/2008"
        xmlns:viewmodel="clr-namespace:MVVMDemo"
    Title="Window1" Height="300" Width="575.851">
    <Window.Resources>
        <viewmodel:ViewModel x:Key="ViewModel"/>
        <viewmodel:DatetimeToDateConverter x:Key="MyConverter"/>
    </Window.Resources>
    <Grid DataContext="{Binding Source={StaticResource ViewModel}}">
        <Grid.RowDefinitions>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="Auto"/>
            <RowDefinition Height="*"/>
        </Grid.RowDefinitions>
        <Grid.ColumnDefinitions>
            <ColumnDefinition Width="Auto"/>
            <ColumnDefinition Width="*"/>
        </Grid.ColumnDefinitions>
        <TextBlock Grid.Row="0" Grid.Column="0" Text="Name" HorizontalAlignment="Center"/>
        <TextBox Grid.Row="0" Grid.Column="1" Width="100" HorizontalAlignment="Center" Text="{Binding Student.Name, Mode=TwoWay}" Margin="76,0"/>
        <TextBlock Grid.Row="1" Grid.Column="0" Text="Age" HorizontalAlignment="Center"/>
        <TextBox Grid.Row="1" Grid.Column="1" Width="100" HorizontalAlignment="Center" Text="{Binding Student.Age, Mode=TwoWay}"/>
        <Button Content="Submit" Command="{Binding SubmitCommand}" HorizontalAlignment="Right" Grid.Row="2" Grid.Column="0"/>

        <ComboBox Grid.Column="1" ItemsSource="{Binding FillCourseId}"  Name="cmb_CourseIDName" HorizontalAlignment="Left" Margin="164.191,5,0,0" 
                  Grid.Row="3" VerticalAlignment="Top" Width="168.342" Grid.RowSpan="2" DataContext="{Binding Source={StaticResource ViewModel}}"  FontSize="8" IsReadOnly="True" 
                  SelectedValue="{Binding Student.SCourseIDName,Mode=TwoWay}" RenderTransformOrigin="1.431,0.77">
            <ComboBox.ItemTemplate>
                <DataTemplate>
                    <StackPanel Orientation="Horizontal" >
                        <TextBlock Text="{Binding Path=CourseName, Mode=TwoWay}" FontSize="12"/>
                        <TextBlock Text=" - "/>
                        <TextBlock Text="{Binding Path=CourseID, Mode=TwoWay}" FontSize="12"/>
                    </StackPanel>
                </DataTemplate>
            </ComboBox.ItemTemplate>

        </ComboBox>
        <ListView ItemsSource="{Binding Students}" Grid.Row="4" Grid.Column="1" Margin="62.551,0,78.762,76.829"
                  ScrollViewer.CanContentScroll="False" 
                 ScrollViewer.VerticalScrollBarVisibility="Visible" Height="85.152" VerticalAlignment="Bottom">
            <ListView.View >
                <GridView  >
                    <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}" Width="60"/>
                    <GridViewColumn  Header="Age" DisplayMemberBinding="{Binding Age}" Width="60"/>
                    <GridViewColumn  Header="Joining Date" DisplayMemberBinding="{Binding JoiningDate, Converter={StaticResource MyConverter}}" Width="80" />
                    <GridViewColumn Header="Course Name" DisplayMemberBinding="{Binding SCourseIDName.CourseName}" Width="80"/>
                    <GridViewColumn Header="CourseId" DisplayMemberBinding="{Binding SCourseIDName.CourseID}" Width="60"/>
                </GridView>
            </ListView.View>
        </ListView>
    </Grid>

</Window>

导出到csv相当简单。您所要做的就是添加每个用逗号(“,”)分隔的数据。这里有一个简单的例子

public string ExportToCsv(IEnumerable<Student> students)
{
    var output = new StringBuilder();
    // Add header if necessary
    output.Append("Name,");
    output.Append("Age ,");
    output.Append("Course ,");
    output.Append("JoiningDate ,");
    output.Append("CourseName ,");
    output.Append("CourseID ,");
    output.AppendLine();
    // Add each row
    foreach (var student in students)
    {
        output.AppendFormat("{0},", student.Name);
        output.AppendFormat("{0},", student.Age);
        output.AppendFormat("{0},", student.Course);
        output.AppendFormat("{0},", student.JoiningDate);
        output.AppendFormat("{0},", student.CourseName);
        output.AppendFormat("{0},", student.CourseID);
        output.AppendLine();
    }
}
公共字符串ExportToCsv(IEnumerable students)
{
var输出=新的StringBuilder();
//如有必要,添加标题
Append(“Name,”);
输出。附加(“年龄”);
输出。追加(“课程”);
output.Append(“JoiningDate”);
output.Append(“CourseName”);
output.Append(“CourseID,”);
AppendLine();
//添加每行
foreach(学生中的var学生)
{
AppendFormat(“{0},”,student.Name);
AppendFormat(“{0},”,student.Age);
AppendFormat(“{0},”,student.Course);
AppendFormat(“{0},”,student.JoiningDate);
AppendFormat(“{0},”,student.CourseName);
AppendFormat(“{0},”,student.CourseID);
AppendLine();
}
}

我想您在页面的某个地方会有一个“导出”按钮?将该按钮绑定到导出命令(与已有的SubmitCommand类似)

Export命令需要获取学生列表(pass作为绑定命令参数,或根据命令所在的位置从引用中传递),并将其输出为CSV(请参见Surendra Shrestha的答案)或Excel。对于编写样式化的Excel,我喜欢ClosedXml nuget包(查看他们的),但是如果您不需要样式,CSV更容易、更快、机器可读,并且可以跨更多系统兼容


如果使用CSV方法,构建CSV字符串后,还需要将其保存为文件。您可以使用
System.IO.File.writeAllines()
方法执行此操作。

您可以在WPF中使用
DataGrid
。在我看来,它比
列表视图
好。如果您有一些使用DataGrid的链接,我建议您将ListView重写为DataGrid。在您的情况下,这应该很容易,当然您可以使用
DataGrid
。有关示例,请参阅博客文章。
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace MVVMDemo
{
    public class Student
    {
        public string Name { get; set; }
        public int Age { get; set; }
        public string Course { get; set; }
        public DateTime JoiningDate { get; set; }
        public string CourseName { get; set; }
        public string CourseID { get; set; }

        public Student SCourseIDName { get; set; }
    }
}
public string ExportToCsv(IEnumerable<Student> students)
{
    var output = new StringBuilder();
    // Add header if necessary
    output.Append("Name,");
    output.Append("Age ,");
    output.Append("Course ,");
    output.Append("JoiningDate ,");
    output.Append("CourseName ,");
    output.Append("CourseID ,");
    output.AppendLine();
    // Add each row
    foreach (var student in students)
    {
        output.AppendFormat("{0},", student.Name);
        output.AppendFormat("{0},", student.Age);
        output.AppendFormat("{0},", student.Course);
        output.AppendFormat("{0},", student.JoiningDate);
        output.AppendFormat("{0},", student.CourseName);
        output.AppendFormat("{0},", student.CourseID);
        output.AppendLine();
    }
}