[英]Export the datagrid in wpf to excel using c#
With the below code I have loaded datagrid
in WPF from ms access DB using c# but not sure how to export the same datagrid
to Excel.使用以下代码,我使用 c# 从 ms access DB 加载了 WPF 中的
datagrid
,但不确定如何将相同的datagrid
导出到 Excel。
try
{
OleDbConnection connect = new OleDbConnection();
connect.ConnectionString =
@"Provider=Microsoft.ACE.OLEDB.12.0;DataSource=|DataDirectory|\Electricalcircuits.mdb";
OleDbCommand cmd = new OleDbCommand();
cmd.CommandType = CommandType.Text;
cmd.CommandText = "Select * from REPORT";
cmd.Connection = connect;
connect.Open();
System.Data.DataTable dt = new System.Data.DataTable();
OleDbDataAdapter DA = new OleDbDataAdapter(cmd);
DA.Fill(dt);
DG1.ItemsSource = dt.AsDataView();
}
catch (OleDbException ex)
{
MessageBox.Show(ex.ToString());
}
To Export the DataGrid into Excel(Csv) on button click using C# in WPF要将 DataGrid 导出到 Excel(Csv) 中的按钮单击使用 WPF 中的 C#
private void btnExport_Click(object sender, RoutedEventArgs e)
{
string ExportName = (sender as System.Windows.Controls.Button).Name.ToString();
bool result = Export.SaveToCSV(TrkDataGrid, ExportName);//pass the Datagrid and Exportname
if (result == true)
{
MessageBoxResult result = System.Windows.MessageBox.Show("Exported successfully", "Information", MessageBoxButton.OK, MessageBoxImage.Information);
}
}
public bool SaveToCSV(System.Windows.Controls.DataGrid dataGrid,string Filename)
{
bool IsVaild = false;
SaveFileDialog saveFileDialog = new SaveFileDialog();
saveFileDialog.Title = "Save CSV Files";
saveFileDialog.Filter = "CSV file (*.csv)|*.csv";
saveFileDialog.FileName = Filename;
string gridname = Filename;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string path = System.IO.Path.GetFullPath(saveFileDialog.FileName);
createcsvfile(dataGrid, path);
IsVaild = true;
}
return IsVaild;
}
private void createcsvfile(System.Windows.Controls.DataGrid dataGrid, string FilePath)
{
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(FilePath, result, UnicodeEncoding.UTF8);
}
You have two ways, you can use the DataTable:你有两种方法,你可以使用DataTable:
How to export DataTable to Excel 如何将数据表导出到 Excel
or you can use the DataGridView "DG1":或者您可以使用 DataGridView“DG1”:
https://code.msdn.microsoft.com/office/How-to-Export-DataGridView-62f1f8ff https://code.msdn.microsoft.com/office/How-to-Export-DataGridView-62f1f8ff
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.