2017-03-30 66 views
-1

我要出口數據網格的WPF但出口出現錯誤時產生導出到數據網格到Excel中的WPF

型「System.NullReferenceException」未處理的異常發生在solutions.exe

我的代碼。 ..

Excel.Application excel = new Excel.Application(); 

     excel.Visible = true; 
     Workbook workbook = excel.Workbooks.Add(System.Reflection.Missing.Value); 
     Worksheet sheet1 = (Worksheet)workbook.Sheets[1]; 
     Range range; 
     Range myRange; 
     for (int i = 1; i < dgDatos.Columns.Count; i++) 
     { 
      range = (Range)sheet1.Cells[1, i + 1]; 
      sheet1.Cells[1, i + 1].Font.Bold = true; 
      range.Value = dgDatos.Columns[i].Header; 

      for (int j = 0; j < dgDatos.Items.Count; j++) 
      { 
       TextBlock b = dgDatos.Columns[i].GetCellContent(dgDatos.Items[j]) as TextBlock; 
       myRange = sheet1.Cells[j + 2, i + 1]; 
       myRange.Value = b.Text; 
      } 
     } 

}

+0

哪一行錯誤指向? –

回答

0

沒有給人NULL值的任何跡象,我的選擇將是對

myRange.Value = b.Text; 

當你這樣做:

TextBlock b = dgDatos.Columns[i].GetCellContent(dgDatos.Items[j]) as TextBlock; 

... b將是無效的,如果分配給該單元格的對象不是TextBlock

對於這個問題,爲什麼在DataGridTextBlock?退房DataTable