WPF DataGrid转csv,只导出网格中可见的值

Sjo*_*ged 3 c# csv wpf xaml datagrid

我对 WPF 还很陌生,想知道是否有可能将 WPF DataGrid 简单地导出到 csv 文件。我尝试使用反射来获取所需的值,尽管这在某种程度上有效,但我想知道是否可以使用附加属性来获取显示的值,这些不一定对应于项目源的值。只要我使用静态字符串或字符串的静态资源等,下面的附加属性就可以工作。如果我尝试使用列绑定,我只会得到一个默认的 string.empty

    public static readonly DependencyProperty ExportStringProperty =
        DependencyProperty.RegisterAttached("ExportString", //name of    attached property
        typeof(string), //type of attached property
        typeof(ExportBehaviour), //type of this owner class
        new PropertyMetadata(string.Empty)); //the default value of the attached property

    public static string GetExportString(DataGridColumn column)
    {
        return (string)column.GetValue(ExportStringProperty);
    }

    public static void SetExportString(DataGridColumn column, string value)
    {
        column.SetValue(ExportStringProperty, value);
    }
Run Code Online (Sandbox Code Playgroud)

是否有类似的方法可以通过以下方式从 xaml 获取绑定值:

    <DataGridTextColumn Header="Name" Binding="{Binding (datagridexcel:Product.Name)}" datagridexcel:ExportBehaviour.ExportString="{Binding (datagridexcel:Product.Name)}"/>
Run Code Online (Sandbox Code Playgroud)

如上所述,以上早先适用于静态类型字符串,而不适用于绑定。必须说在这种情况下应该避免使用项目源,我唯一感兴趣的是数据网格和那里显示的值。

Sza*_*zsi 5

我制作了这个简单的应用程序来演示一种从DataGrid. 你有DataGrid

<DataGrid x:Name="MyDataGrid" Grid.Row="0" ItemsSource="{Binding Rows}" />
Run Code Online (Sandbox Code Playgroud)

在此示例中,它绑定到视图模型中的以下属性:

private IEnumerable<RowViewModel> _rows;
public IEnumerable<RowViewModel> Rows
{
    get { return _rows; }
    set
    {
        _rows = value;
        OnPropertyChanged("Rows");
    }
}
Run Code Online (Sandbox Code Playgroud)

行设置为以下示例数据:

Rows = new List<RowViewModel>
{
    new RowViewModel { FirstName = "John", LastName = "Doe", DateOfBirth = new DateTime(1988, 12, 19) },
    new RowViewModel { FirstName = "Lara", LastName = "Croft", DateOfBirth = new DateTime(1975, 5, 3) },
    new RowViewModel { FirstName = "Sam", LastName = "Fisher", DateOfBirth = new DateTime(1967, 2, 9) }
};
Run Code Online (Sandbox Code Playgroud)

DataGrid我有一个Button

<Button Grid.Row="1" Content="Copy values as CSV" Command="{Binding CopyAsCsvCommand}" CommandParameter="{Binding ElementName=MyDataGrid}" />
Run Code Online (Sandbox Code Playgroud)

它绑定到Command视图模型中的 a 并且CommandParameter是整个DataGrid.

CopyAsCsvCommand = new DelegateCommand<DataGrid>(CopyAsCsvHandler);
Run Code Online (Sandbox Code Playgroud)

Command的处理方法,其中实际发生的复制:

private void CopyAsCsvHandler(DataGrid dg)
{
    dg.SelectAllCells();
    dg.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
    ApplicationCommands.Copy.Execute(null, dg);
    dg.UnselectAllCells();
    LivePreviewText = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
}
Run Code Online (Sandbox Code Playgroud)

这等效于使用 CTRL+A 选择所有单元格并按 CTRL+C。

例子

示例图像

现在您有了 CSV 内容,您可以将其保存到一个带有 CSV 扩展名的文件中。我希望这会有所帮助,这就是您要寻找的。