We use cookies to give you the best experience on our website. If you continue to browse, then you agree to our privacy policy and cookie policy. Image for the cookie policy date

NullReferenceException on ExportToExcel

Hey,

I am facing issues in exporting to excel from SfDataGrid. It gives a null reference exception on this line:

var excelEngine = StudentsDataGrid.ExportToExcel(StudentsDataGrid.View, options);

The exception message and StackTrace is as mentioned below:

Message: "Object reference not set to an instance of an object."

Source: "Syncfusion.SfGridConverter.WPF"

StackTrace: "   at Syncfusion.UI.Xaml.Grid.Converter.SfDataGridToExcelConverter.ExportDetailsViewToExcel(SfDataGrid parentDataGrid, IWorksheet sheet, ExcelExportingOptions excelExportingOptions, Object rec, IPropertyAccessProvider propertyAccessProvider)\r   at Syncfusion.UI.Xaml.Grid.Converter.SfDataGridToExcelConverter.ExportRecordsToExcel(SfDataGrid grid, IWorksheet sheet, ExcelExportingOptions excelExportingOptions, IEnumerable records, IPropertyAccessProvider propertyAccessProvider, Group group)\r   at Syncfusion.UI.Xaml.Grid.Converter.SfDataGridToExcelConverter.ExportToExcelWorksheet(SfDataGrid grid, ICollectionViewAdv view, IWorksheet sheet, ExcelExportingOptions excelExportingOptions)\r   at Syncfusion.UI.Xaml.Grid.Converter.SfDataGridToExcelConverter.ExportToExcel(SfDataGrid grid, ICollectionViewAdv view, ExcelExportingOptions excelExportingOptions)\r   at Syncfusion.UI.Xaml.Grid.Converter.GridExcelExportExtension.ExportToExcel(SfDataGrid grid, ICollectionViewAdv gridCollectionView, ExcelExportingOptions excelExportingOptions)\r   at MainModule.Views.FacultyHome.ExportStudentsClick(Object sender, RoutedEventArgs e) in E:\\MyApps\\AtomV2\\MainModule\\Views\\FacultyHome.xaml.cs:line 27\r   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)\r   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)\r   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)\r   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs e)\r   at System.Windows.Controls.Primitives.ButtonBase.OnClick()\r   at System.Windows.Controls.Button.OnClick()\r   at System.Windows.Controls.Primitives.ButtonBase.OnMouseLeftButtonUp(MouseButtonEventArgs e)\r   at System.Windows.UIElement.OnMouseLeftButtonUpThunk(Object sender, MouseButtonEventArgs e)\r   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)\r   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)\r   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)\r   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)\r   at System.Windows.UIElement.ReRaiseEventAs(DependencyObject sender, RoutedEventArgs args, RoutedEvent newEvent)\r   at System.Windows.UIElement.OnMouseUpThunk(Object sender, MouseButtonEventArgs e)\r   at System.Windows.Input.MouseButtonEventArgs.InvokeEventHandler(Delegate genericHandler, Object genericTarget)\r   at System.Windows.RoutedEventArgs.InvokeHandler(Delegate handler, Object target)\r   at System.Windows.RoutedEventHandlerInfo.InvokeHandler(Object target, RoutedEventArgs routedEventArgs)\r   at System.Windows.EventRoute.InvokeHandlersImpl(Object source, RoutedEventArgs args, Boolean reRaised)\r   at System.Windows.UIElement.RaiseEventImpl(DependencyObject sender, RoutedEventArgs args)\r   at System.Windows.UIElement.RaiseTrustedEvent(RoutedEventArgs args)\r   at System.Windows.UIElement.RaiseEvent(RoutedEventArgs args, Boolean trusted)\r   at System.Windows.Input.InputManager.ProcessStagingArea()\r   at System.Windows.Input.InputManager.ProcessInput(InputEventArgs input)\r   at System.Windows.Input.InputProviderSite.ReportInput(InputReport inputReport)\r   at System.Windows.Interop.HwndMouseInputProvider.ReportInput(IntPtr hwnd, InputMode mode, Int32 timestamp, RawMouseActions actions, Int32 x, Int32 y, Int32 wheel)\r   at System.Windows.Interop.HwndMouseInputProvider.FilterMessage(IntPtr hwnd, WindowMessage msg, IntPtr wParam, IntPtr lParam, Boolean& handled)\r   at System.Windows.Interop.HwndSource.InputFilterMessage(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)\r   at MS.Win32.HwndWrapper.WndProc(IntPtr hwnd, Int32 msg, IntPtr wParam, IntPtr lParam, Boolean& handled)\r   at MS.Win32.HwndSubclass.DispatcherCallbackOperation(Object o)\r   at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)\r   at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)"

TargetSite: {Void ExportDetailsViewToExcel(Syncfusion.UI.Xaml.Grid.SfDataGrid, Syncfusion.XlsIO.IWorksheet, Syncfusion.UI.Xaml.Grid.Converter.ExcelExportingOptions, System.Object, Syncfusion.Data.IPropertyAccessProvider)}


Thanks in advance for the help!

Regards
Ahmad Uzair



9 Replies

AK Adhikesevan Kothandaraman Syncfusion Team June 7, 2019 02:43 PM UTC

Hi Ahmad,  

Thanks for using Syncfusion products.  
   
We have analyzed your reported scenario at our end. We need some more information regarding this to investigate this further. Can you please provide It’s the manually generated details view or auto generated. 
and also please confirm your essential studio version. It will be helpful for us to provide the solution at the earliest. 

Regards,  
Adhi 



AH Ahmad June 8, 2019 06:52 PM UTC

Hey Adhi,

Thanks for the prompt response. I am using the Essential Studio Version 17.1.0.47, the latest one. I had updated it yesterday.

And this exception was automatically given by visual studio when it breaks. I have copied the source, target site and stacktrace from there.

Hope this helps to resolve the issue.

Regards
Ahmad Uzair


JP Jagadeesan Pichaimuthu Syncfusion Team June 10, 2019 09:50 AM UTC

Hi Ahmad, 
  
Thanks for the update. 
  
We cannot replicate the reported issue from our end. We found that exception happens in the export of DetailsView from the specified StackTrace. And in our end, this case works fine. 
  
Please find tested sample from our end in the below link. 
  
Could you kindly share with us the below information to reproduce the reported issue from our end. 
  
1. Have you made any customization in SfDataGrid while exporting? If yes, kindly share the code file 
2. For DetailsView, do you manually define relationships or auto-generated relationships? 
3. ReplicationProcedure / Illustration of video to reproduce the reported issue. 
  
Also if possible please revert us with the modified sample. It will be help us to further investigate and provide earlier timely solutions. 
  
Regards, 
Jagadeesan 



AH Ahmad June 13, 2019 04:37 PM UTC

Hey!

Sorry for the late response. I am manually defning the details view. I am trying to export 2 different datagrids. The code is as mentioned below:

Data Grid 1:

<Button Content="Export to Excel" Click="ExportStudentsClick"/>
                        <dataGrid:SfDataGrid ItemsSource="{Binding Students}" Name="StudentsDataGrid" AutoGenerateColumns="False" ColumnSizer="Star" ScrollMode="Async" >

                        <dataGrid:SfDataGrid.Columns>
                            <dataGrid:GridTextColumn MappingName="UserId" HeaderText="ID No"/>
                            <dataGrid:GridTextColumn MappingName="Name" HeaderText="Name"/>
                        </dataGrid:SfDataGrid.Columns>
                        <dataGrid:SfDataGrid.SortColumnDescriptions>
                            <dataGrid:SortColumnDescription ColumnName="Id"/>
                            <dataGrid:SortColumnDescription ColumnName="name"/>
                        </dataGrid:SfDataGrid.SortColumnDescriptions>
                        <dataGrid:SfDataGrid.DetailsViewDefinition >
                            <dataGrid:TemplateViewDefinition RowTemplate="{StaticResource StudentDetailViewTemplate}">

                            </dataGrid:TemplateViewDefinition>
 </dataGrid:SfDataGrid.DetailsViewDefinition>
                    </dataGrid:SfDataGrid>
                    </StackPanel>

Details View:

<DataTemplate x:Key="StudentDetailViewTemplate">
            <Grid>
                <Grid.ColumnDefinitions>
                    <ColumnDefinition/>
                    <ColumnDefinition/>
                </Grid.ColumnDefinitions>
                <StackPanel>
                    <TextBlock Text="Quiz 1: " FontWeight="DemiBold"/>
                    <TextBlock Text="Quiz 2: " FontWeight="DemiBold"/>
                    <TextBlock Text="Quiz 3: " FontWeight="DemiBold"/>
                    <TextBlock Text="Quiz 4: " FontWeight="DemiBold"/>
                    <TextBlock Text="Quiz 5: " FontWeight="DemiBold"/>
                    <TextBlock Text="Quiz 6: " FontWeight="DemiBold"/>
                    <TextBlock Text="Quiz 7: " FontWeight="DemiBold"/>
                    <TextBlock Text="Quiz 8: " FontWeight="DemiBold"/>
                    <TextBlock Text="Quiz 9: " FontWeight="DemiBold"/>
                    <TextBlock Text="Quiz 10: " FontWeight="DemiBold"/>
                </StackPanel>
                <StackPanel Grid.Column="1">
                    <TextBlock Text="{Binding Data.Q1,Converter={StaticResource ScoreToNotAttemptedConverter}}"/>
                    <TextBlock Text="{Binding Data.Q2,Converter={StaticResource ScoreToNotAttemptedConverter}}"/>
                    <TextBlock Text="{Binding Data.Q3,Converter={StaticResource ScoreToNotAttemptedConverter}}"/>
                    <TextBlock Text="{Binding Data.Q4,Converter={StaticResource ScoreToNotAttemptedConverter}}"/>
                    <TextBlock Text="{Binding Data.Q5,Converter={StaticResource ScoreToNotAttemptedConverter}}"/>
                    <TextBlock Text="{Binding Data.Q6,Converter={StaticResource ScoreToNotAttemptedConverter}}"/>
                    <TextBlock Text="{Binding Data.Q7,Converter={StaticResource ScoreToNotAttemptedConverter}}"/>
                    <TextBlock Text="{Binding Data.Q8,Converter={StaticResource ScoreToNotAttemptedConverter}}"/>
                    <TextBlock Text="{Binding Data.Q9,Converter={StaticResource ScoreToNotAttemptedConverter}}"/>
                    <TextBlock Text="{Binding Data.Q10,Converter={StaticResource ScoreToNotAttemptedConverter}}"/>
                </StackPanel>

            </Grid>
        </DataTemplate>

Exporting Event Handler:

private void ExportStudentsClick(object sender, RoutedEventArgs e)
            {
                try
                {

              
                var options = new ExcelExportingOptions();
                options.ExcelVersion = ExcelVersion.Excel2016;
                options.ExportMode = ExportMode.Text;
                //options.ChildExportingEventHandler = ChildExportingHandler;
                var excelEngine = StudentsDataGrid.ExportToExcel(StudentsDataGrid.View, options);
               
                var workBook = excelEngine.Excel.Workbooks[0];
                SaveFileDialog sfd = new SaveFileDialog
                {
                    Filter = "Excel File(*.xlsx)|*.xlsx"
                };


                if (sfd.ShowDialog() == true)
                {
                    using (Stream stream = sfd.OpenFile())
                    {
                        workBook.Version = ExcelVersion.Excel2016;
                        workBook.SaveAs(stream);
                    }
                }

                //Message box confirmation to view the created workbook.

                if (MessageBox.Show("Do you want to view the workbook?", "Workbook has been created",
                        MessageBoxButton.YesNo, MessageBoxImage.Information) == MessageBoxResult.Yes)
                {

                    //Launching the Excel file using the default Application.[MS Excel Or Free ExcelViewer]
                    System.Diagnostics.Process.Start(sfd.FileName);
                }

                excelEngine.Dispose();
                }
                catch (Exception exception)
                {
                    MessageBox.Show("Unable to Export to Excel", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
                }
            }


AH Ahmad June 13, 2019 04:39 PM UTC

Data Grid 2:

<dataGrid:SfDataGrid ItemsSource="{Binding Questions}" AutoGenerateColumns="False" Name="QuestionsDataGrid">
                        <dataGrid:SfDataGrid.Columns>
                            <dataGrid:GridTextColumn MappingName="QsText" HeaderText="Question"/>
                            <dataGrid:GridTextColumn MappingName="QuestionType" HeaderText="Question Type"/>
                            <dataGrid:GridTextColumn MappingName="ExperimentNo" HeaderText="Experiment No"/>

                        </dataGrid:SfDataGrid.Columns>
 <dataGrid:SfDataGrid.DetailsViewDefinition>
                          <dataGrid:TemplateViewDefinition RowTemplate="{StaticResource AnswersGridTemplate}"></dataGrid:TemplateViewDefinition>
                      </dataGrid:SfDataGrid.DetailsViewDefinition>
</dataGrid:SfDataGrid>

Details View:

<DataTemplate x:Key="AnswersGridTemplate">
    <dataGrid:SfDataGrid ItemsSource="{Binding Data.Options, Converter={StaticResource EmptyConverter}}" AutoGenerateColumns="False">
        <dataGrid:SfDataGrid.Columns>
            <dataGrid:GridTextColumn MappingName="AnswerText" HeaderText="Answer"/>
            <dataGrid:GridCheckBoxColumn MappingName="IsCorrect" HeaderText="Correct Option"></dataGrid:GridCheckBoxColumn>
        </dataGrid:SfDataGrid.Columns>
    </dataGrid:SfDataGrid>
</DataTemplate>





JP Jagadeesan Pichaimuthu Syncfusion Team June 14, 2019 09:45 AM UTC

Hi Ahmed, 
  
Thanks for the update. 
  
We have analyzed the code snippet that you have provided and found that you are using TemplateViewDefinition in your application. We regret to inform you that SfDataGrid does not have support for exporting TemplateViewDefinition to Excel. However, the reported exception should not be thrown. So we have logged bug report to handle the reported exception in our end. The fix for the reported issue will be available in our upcoming 2019 Volume 2 Main release which is expected to be rolled out at the end of June,2019. 
  
Could you please let us know, whether you would be waiting for our official release? Otherwise, we will provide patch for the reported issue. 
  
Also we have created feedback for the reported issue and we request you to login to the below link to view further. 
  
Regards, 
Jagadeesan 



AH Ahmad June 14, 2019 11:22 AM UTC

Hey Jagadeesan!

Thank you so much for the help! I would prefer to get the fix ASAP as i need to deliver this project in next 2 weeks. 

Hope you understand. Thanks again.

Regards
Ahmad Uzair


DB Dinesh Babu Yadav Syncfusion Team June 17, 2019 06:37 AM UTC

Hi Ahmad, 
 
Thanks for the update. 
 
As per your request, we have given high priority to the reported bug and the patch for the issue will be given on 28th June, 2019 and the fix for the reported issue will be available in our upcoming 2019 Volume 2 Main release which is expected to be rolled out at the end of June,2019. 
 
Regards, 
Dinesh Babu Yadav 



FP Farjana Parveen Ayubb Syncfusion Team June 28, 2019 10:19 AM UTC

Hi Ahmed, 
  
Thanks for your patience. 
  
We have fixed the reported “Null reference exception occurs when export to excel with TemplateViewDefinition” issue in your version (17.1.0.47).  Please find the patch file for this from the below link. 

Recommended approach - exe will perform automatic configuration
Please find the patch setup from below location:
 
http://syncfusion.com/Installs/support/patch/17.1.0.47/1080462/F145091/SyncfusionPatch_17.1.0.47_1080462_6282019031243692_F145091.exe

Advanced approach – use only if you have specific needs and can directly replace existing assemblies for your build environment
Please find the patch assemblies alone from below location:
 
Please find Nuget packages from below location: 

Assembly Version: 17.1.0.47
 
Installation Directions: 
This patch should replace the files “SfGridConverter.WPF” under the following folder.
$system drive:\ Files\Syncfusion\Essential Studio\$Version # \precompiledassemblies\$Version#\4.6
Eg : $system drive:\Program Files\Syncfusion\Essential Studio\17.1.0.47\precompiledassemblies\17.1.0.47\4.6

To automatically run the Assembly Manager, please check the Run assembly manager checkbox option while installing the patch. If this option is unchecked, the patch will replace the assemblies in precompiled assemblies’ folder only. Then, you will have to manually copy and paste them to the preferred location or you will have to run the Syncfusion Assembly Manager application (available from the Syncfusion Dashboard, installed as a shortcut in the Application menu) to re-install assemblies.

Note
You can change how you receive bug fixes by navigating to the following link and updating your preferences.

https://www.syncfusion.com/support/directtrac/patches

Disclaimer
Please note that we have created this patch for version 17.1.0.47 specifically to resolve the following issue(s) reported in this/the forum(s). 145091

If you have received other patches for the same version for other products, please apply all patches in the order received.
 

This fix for the reported issue is included in our Essential studio 2019 Volume 2 Beta Release version 17.2.0.28 and is available for download under the following link.
  
  
  
Note: This issue fix will be included in our main release as well which is expected to be available by mid of July 2019.  
  
Please let us know, if you have any concern. 
 
Regards, 
Farjana Parveen A 


Loader.
Live Chat Icon For mobile
Up arrow icon