我正在嘗試將數據從WPF DataGrid導出到Excel文檔中。當我運行這個按鈕時,它會輸出在屏幕上可見的或者適合窗口的所有內容。 DataGrid已經足夠了,你必須向下滾動才能看到所有的值,這些隱藏的值不會導出到excel文檔中,並且錯誤「對象引用未設置爲對象的實例」。發生。如果所有的值都適合在屏幕上,那就沒有問題了。將所有DataGrid行(包括不可見)WPF導出到Excel
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;
}
}
爲什麼不從DataGrid的DataContext/ItemsSource中抽取數據,因爲它包含了所有內容?直接從UI控件而不是從視圖模型拉動它很奇怪。 – hoodaticus