Introduction
Here in this blog, we will see how to export datagrid to excel C# WPF and WPF datagrid export to CSV without using any library or third party library.
WPF DataGrid Export to Excel |
Getting Started
Lets say you have a WPF datagrid where you are populating list of data like below image in your project for reporting or any other purpose. You want export the populated data from WPF datagrid to excel or csv file with help of a button.
WPF DataGrid Export to Excel |
We will see how to export populated data from WPF Datagrid to CSV files using the clipboard rather than using any library. On the button click event we will copy WPF Datagrid data into clipboard then will export it to CSV file. The following code helps copy the WPF Datagrid data into the clipboard.
this.dgvStudents.SelectAllCells();
this.dgvStudents.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null, this.dgvStudents);
this.dgvStudents.UnselectAllCells();
The below code snippet helps to retrieve data from clipboard then same it into csv file.
String result = (string) Clipboard.GetData(DataFormats.CommaSeparatedValue);
try
{
StreamWriter sw = new StreamWriter("wpfdata.csv");
sw.WriteLine(result);
sw.Close();
Process.Start("wpfdata.csv");
}
catch(Exception ex)
{}
Above are the two code examples which actually export the populated data in WPF Datagrid into CSV file. Now will demonstrate how to achieve WPF Datagrid to excel in WPF project.
Demonstration
Open your WPF project where you want to export data from WPF Datagrid to excel, go that container control(WPF Windows or WPF User control) where you have used Datagrid which data you want to export.
I hope that you have already taken a button in your project for the purpose of data exportation or if you have taken any other control , in the event put the below code. For example, if you want to export data in the button click event then put the below code in the button event.
private void Button_Click_1(object sender, RoutedEventArgs e)
{
this.dgvStudents.SelectAllCells();
this.dgvStudents.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null, this.dgvStudents);
this.dgvStudents.UnselectAllCells();
String result = (string) Clipboard.GetData(DataFormats.CommaSeparatedValue);
try
{
StreamWriter sw = new StreamWriter("wpfdata.csv");
sw.WriteLine(result);
sw.Close();
Process.Start("wpfdata.csv");
}
catch(Exception ex)
{}
}
The above code example in the button click event, contains all the code that copies WPF datagrid populated data into clipboard by selecting all the cells of WPF datagrid then with help of StreamWriter class exports to csv file("wpfdata.csv"). After saving data into file, it opens the csv file in Excel application.
Go and see the below full code, if you have doubts. The full code is given by separating classes for better understanding, you can use this classes to build demo project.
Main Window XAML
<Window x:Class="WPFDataGridExport.MainWindow" xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation" xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml" Title="MainWindow" Height="350" Width="525">
<DockPanel>
<StackPanel Orientation="Horizontal" FlowDirection="RightToLeft" DockPanel.Dock="Bottom">
<Button Content="Export" Click="Button_Click_1" Margin="5"></Button>
</StackPanel>
<DataGrid AutoGenerateColumns="False" Name="dgvStudents">
<DataGrid.Columns>
<DataGridTextColumn Header="Name" Width="*" Binding="{Binding Path=Name, Mode=Default}"></DataGridTextColumn>
<DataGridTextColumn Header="Roll no." Width="100" Binding="{Binding Path=RollNo, Mode=Default}"></DataGridTextColumn>
<DataGridTextColumn Header="Age" Width="100" Binding="{Binding Path=Age, Mode=Default}"></DataGridTextColumn>
</DataGrid.Columns>
</DataGrid>
</DockPanel>
</Window>
Student Class
public class Student
{
public string Name { get; set; }
public int RollNo { get; set; }
public int Age { get; set; }
}
Main Window CS
namespace wpfexporttoexcel
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
{
public List<Student> Students
{
get;
set;
}
public MainWindow()
{
InitializeComponent();
FillDate();
}
private void Button_Click_1(object sender, RoutedEventArgs e)
{
this.dgvStudents.SelectAllCells();
this.dgvStudents.ClipboardCopyMode = DataGridClipboardCopyMode.IncludeHeader;
ApplicationCommands.Copy.Execute(null, this.dgvStudents);
this.dgvStudents.UnselectAllCells();
String result = (string)Clipboard.GetData(DataFormats.CommaSeparatedValue);
try
{
StreamWriter sw = new StreamWriter("export.csv");
sw.WriteLine(result);
sw.Close();
Process.Start("export.csv");
}
catch (Exception ex)
{ }
}
private void FillDate()
{
this.Students = new List<Student>();
this.Students.Add(new Student()
{
Name = "Kailash",
RollNo = 1,
Age = 10
});
this.Students.Add(new Student()
{
Name = "Munna",
RollNo = 2,
Age = 10
});
this.Students.Add(new Student()
{
Name = "Suraj",
RollNo = 3,
Age = 10
});
this.Students.Add(new Student()
{
Name = "Kiran",
RollNo = 4,
Age = 10
});
this.Students.Add(new Student()
{
Name = "Akash",
RollNo = 5,
Age = 10
});
this.Students.Add(new Student()
{
Name = "Vishal",
RollNo = 6,
Age = 10
});
this.Students.Add(new Student()
{
Name = "Manoj",
RollNo = 7,
Age = 10
});
this.Students.Add(new Student()
{
Name = "Ajay",
RollNo = 8,
Age = 10
});
this.Students.Add(new Student()
{
Name = "Rushi",
RollNo = 9,
Age = 10
});
this.Students.Add(new Student()
{
Name = "Ruchit",
RollNo = 10,
Age = 10
});
this.dgvStudents.ItemsSource = this.Students;
}
}
}
Summary
In the above example we saw how to export data from WPF DataGrid to CSV file, I hope you have enjoyed it a lot.
Thanks