我想将datagrid导出为具有以下格式的txt文件:
//inside txt file, each item on one row
item1[id],item1[name]
item2[id],item2[name]
类似的东西,每一行都用逗号分隔。 目前,我的代码是这样的:
var directory = Path.GetDirectoryName(Assembly.GetEntryAssembly().Location);
var file = Path.Combine(directory, "123.txt");
StringBuilder strBuilder = new StringBuilder();
for (int i = 0; i < datagrid.Items.Count; i++)
{
////////My Setting class
Setting setting= (Setting)datagrid.Items[i];
//////// I need help for the below lines with formatting
strBuilder.Append(setting.id);
strBuilder.Append(setting.name);
}
File.WriteAllText(file, strBuilder.ToString());
我的第二个问题是:123.txt文件的输出目录位于bin / debug文件夹中,我可以将其更改为项目的当前工作目录/工作空间吗?
答案 0 :(得分:0)
使用此链接获取详细信息示例export-data-from-a-datagrid或此exporting-datagrid-to-csv-without-a-gui-in-wpf
或者如果您只想导出,请使用以下代码:
private void button_Click(object sender, RoutedEventArgs e)
{
dataGrid1.SelectAllCells();
dataGrid1.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null, dataGrid1);
dataGrid1.UnselectAllCells();
String result = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
File.AppendAllText("D:\\test.csv", result, UnicodeEncoding.UTF8);
}
对于路径问题,请使用“ .. \” how-to-navigate-a-few-folders-up