I'm trying to export a WPF datagrid to an Excel sheet, but I keep getting errors. I have found this examples, but I don't know how to export from an observablecollection. In this example it seems that there is a list. So I think I have to cast from list to observablecollection, but I can't get it right. I'm still new to functionality in C# and WPF, so any help is very appreciated.
http://www.codeproject.com/Articles/120480/Export-to-Excel-Functionality-in-WPF-DataGrid
My code
private ObservableCollection<T_P> _observableCollection;
private CollectionViewSource _collectionViewSource;
public ExportExcel()
{
InitializeComponent();
using (var dc = new DataClasses2DataContext())
{
_observableCollection = new ObservableCollection<T_P>(dc.T_Ps);
}
_collectionViewSource = (CollectionViewSource)this.FindResource("_T_PViewSource") as CollectionViewSource;
_collectionViewSource.Source = _observableCollection;
this.T_P = new T_P();
this.DataContext = T_P;
}
private void btnExportExcel_Click(object sender, RoutedEventArgs e)
{
ExportToExcel();
//some code here?
}
// How can I call this class?
public class ExportToExcel<T>
where T : class
{
public List<T> dataToPrint;
// Excel object references.
private Excel.Application _excelApp = null;
private Excel.Workbooks _books = null;
private Excel._Workbook _book = null;
private Excel.Sheets _sheets = null;
private Excel._Worksheet _sheet = null;
private Excel.Range _range = null;
private Excel.Font _font = null;
// Optional argument variable
private object _optionalValue = Missing.Value;
//......
Your code is incomplete so it's hard to tell, but it goes along these lines:
private void btnExportExcel_Click(object sender, RoutedEventArgs e)
{
var exporter = new ExportToExcel<T_P>()
{
dataToPrint = new List<T_P>(_observableCollection);
};
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.