在WPf中导出到DataGrid到Excel

时间:2017-03-30 00:08:37

标签: c# wpf datagrid

我希望将datagrid导出到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;
            }
        }

}

1 个答案:

答案 0 :(得分:1)

如果没有给出任何空值的指示,我的赌注就是

myRange.Value = b.Text;

执行此操作时:

TextBlock b = dgDatos.Columns[i].GetCellContent(dgDatos.Items[j]) as TextBlock;
如果分配给该单元格的对象不是b,则

... TextBlock将为null。

就此而言,为什么TextBlock中有DataGrid?查看DataTable