简体   繁体   English

将 wpf 数据网格导出到自定义 Excel CSV 文件

[英]Exporting wpf datagrid into custom Excel CSV file

I have a wpf datagrid which is bound to a MVVM collection class.我有一个 wpf 数据网格,它绑定到 MVVM 集合 class。 And I have some properties of MVVM class which is bound to datagrid but not every.而且我有一些绑定到数据网格的 MVVM class 属性,但不是每个属性。

I need to export data in Excel CSV file from the datagrid.我需要从数据网格中导出 Excel CSV 文件中的数据。 But there are some properties of the MVVM class which are not bound to datagrid but need to be shown in Excel file.但是 MVVM class 的一些属性未绑定到数据网格,但需要在 Excel 文件中显示。 So I need to create custom columns (columns from datagrid+some extra).所以我需要创建自定义列(来自datagrid的列+一些额外的)。

Here is the code I am using currently to create the Excel CSV file:这是我目前用来创建 Excel CSV 文件的代码:

importedDG.SelectAllCells(); 
importedDG.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null, importedDG);
importedDG.UnselectAllCells();
string path1 = "C:\\test.csv"; 
string result1 = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue); 
Clipboard.Clear(); 
System.IO.StreamWriter file1 = new System.IO.StreamWriter(path1);
file1.WriteLine(result1);file1.Close(); 

This creates the file with the exact columns from the DG but not extra which I want.这将创建具有来自 DG 的确切列的文件,但不是我想要的额外列。 How can I add them?我怎样才能添加它们?

I'm guessing you're using a method on the grid control to produce the CSV?我猜您正在使用网格控件上的方法来生成 CSV? You've not stated as much in your question.你在你的问题中没有说太多。

If so, I would move this responsibility to your view model.如果是这样,我会把这个责任转移到你的观点 model 上。 You can use a CSV library such as KBCsv to perform the task of writing your data.您可以使用 CSV 库(例如KBCsv )来执行写入数据的任务。

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

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