思路为:全选中datagrid表格中的内容,直接拷贝出来。
在导出按钮的Click事件中写入以下代码:
DataGrid dataGrid = paramArray as DataGrid;
string fileName = System.AppDomain.CurrentDomain.BaseDirectory+"开关量" +DateTime.Now.ToString("yyyy-MM-dd HHmmss")+".csv";
string strFormat = fileName;
dataGrid.SelectAllCells();
dataGrid.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null, dataGrid);
dataGrid.UnselectAllCells();
string result = (string)System.Windows.Clipboard.GetData(System.Windows.DataFormats.CommaSeparatedValue);
File.AppendAllText(strFormat, result, UnicodeEncoding.UTF8); Clipboard.Clear();//清空粘贴板
MessageBox.Show("导出成功");
//注释部分是导出后提示是否打开查看功能
// var messageBoxResult = System.Windows.MessageBox.Show("导出成功,是否查看报告?", "提示",
// MessageBoxButton.YesNo, MessageBoxImage.Information, System.Windows.MessageBoxResult.No, System.Windows.MessageBoxOptions.ServiceNotification);
//if (messageBoxResult == MessageBoxResult.Yes)
//{
// Process.Start(fileName);
//}
网友评论