I am trying to export data from a WPF DataGrid into an excel document. When I run this button, it exports everything that is visible on the screen and or fits in the window. The DataGrid is filled enough that you have to scroll down to see all the values, these hidden values are not exported into the excel document and the error "Object reference not set to an instance of an object." occurs. If all the values fit on the screen, there is no problem.
private void Button_Click(object sender, RoutedEventArgs e)
{
Excel.Application excel = new Excel.Application();
excel.Visible = true;
Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value);
Worksheet sheet1 = (Worksheet)workbook.Sheets[1];
for (int ExcelRow = 1, GridRow = 0; ExcelRow <= dgrid.Items.Count - 1;
ExcelRow++, GridRow++)
{
Range myRange = (Range)sheet1.Cells[ExcelRow, 1];
myRange.Value2 = dgrid.Columns[0].Header;
TextBlock b = dgrid.Columns[0].GetCellContent(dgrid.Items[GridRow])
as TextBlock;
Microsoft.Office.Interop.Excel.Range myRange2 =
(Microsoft.Office.Interop.Excel.Range)sheet1.Cells[2, 1];
myRange.Value2 = b.Text;
///////////////////////
myRange = (Range)sheet1.Cells[ExcelRow, 2];
myRange.Value2 = dgrid.Columns[1].Header;
b = dgrid.Columns[1].GetCellContent(dgrid.Items[GridRow]) as
TextBlock;
myRange2 = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[3, 2];
myRange.Value2 = b.Text;
/////////////////////////
myRange = (Range)sheet1.Cells[ExcelRow, 3];
myRange.Value2 = dgrid.Columns[2].Header;
b = dgrid.Columns[2].GetCellContent(dgrid.Items[GridRow]) as
TextBlock;
myRange2 = (Microsoft.Office.Interop.Excel.Range)sheet1.Cells[4, 3];
myRange.Value2 = b.Text;
}
}