private void btnExportToExcel_Click(object sender, RoutedEventArgs e) { ExportDataToExcel ex = new ExportDataToExcel(); ex.ExportToExcel(); } public Microsoft.Office.Interop.Excel.Application ExportToExcel() { int i = 0; int j = 0; int k = 1; j=dgDisplay.Items.Count;//it returns j=0..what went wrong? var rows = GetDataGridRows(dgDisplay); Microsoft.Office.Interop.Excel.Application ExcelApp = new Microsoft.Office.Interop.Excel.Application(); Microsoft.Office.Interop.Excel._Workbook ExcelBook; Microsoft.Office.Interop.Excel._Worksheet ExcelSheet; ExcelBook = (Microsoft.Office.Interop.Excel._Workbook)ExcelApp.Workbooks.Add(1); ExcelSheet = (Microsoft.Office.Interop.Excel._Worksheet)ExcelBook.ActiveSheet; for (i = 1; i <= dgDisplay.Columns.Count; i++) { ExcelSheet.Cells[1, i] = dgDisplay.Columns[i - 1].Header.ToString(); } foreach (DataGridRow r in rows) { DataRowView rv = (DataRowView)r.Item; foreach (DataGridColumn column in dgDisplay.Columns) { if (column.GetCellContent(r) is TextBlock) { TextBlock cellContent = column.GetCellContent(r) as TextBlock; ExcelSheet.Cells[i + 1, k] = cellContent.Text.Trim(); k++; //MessageBox.Show(cellContent.Text); } } } ExcelApp.Visible = true; ExcelSheet = null; ExcelBook = null; ExcelApp = null; return ExcelApp; } public IEnumerable<DataGridRow> GetDataGridRows(DataGrid grid) { var itemsSource = grid.ItemsSource as IEnumerable; if (null == itemsSource) yield return null; foreach (var item in itemsSource) { var row = grid.ItemContainerGenerator.ContainerFromItem(item) as DataGridRow; if (null != row) yield return row; } }
var
This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)