This is a migrated thread and some comments may be shown as answers.

MVVM RadGridView Export create zero size file

10 Answers 215 Views
GridView
This is a migrated thread and some comments may be shown as answers.
herb
Top achievements
Rank 1
Veteran
Iron
herb asked on 24 Nov 2020, 04:43 PM

     Struggling to mimic the Grid View Exporting to Xlsx and Pdf example in the DEMO to understand how to build this function in a project. For the most part I have created the a working code but two things happens.

1) I get zero bit excel file.

2) In the code get System.ArgumentException "Please provide GridViewDataControl for exporting!". Sure enough in "var grid = param as RadGridView;" Param looks good bu the "grid" is null. Not sure how to over come.

When I run the demo program for the first time and open the xlsx file I'm getting something about the formatting is not correct... 

 
private void Export(object param)
        {
            var grid = param as RadGridView;
            var dialog = new SaveFileDialog()
            {
                DefaultExt = this.SelectedExportFormat,
                Filter = String.Format("(*.{0})|*.{1}", this.SelectedExportFormat, this.SelectedExportFormat)
            };
 
            if (dialog.ShowDialog() == true)
            {
                using (var stream = dialog.OpenFile())
                {
                    switch (this.SelectedExportFormat)
                    {
                        case "xlsx":
                            grid.ExportToXlsx(stream);
                            break;
                        case "pdf":
                            //grid.ExportToPdf(stream);
                            break;
                    }
                }
            }
        }
::
private void ExportDefaultStyles(object param)
        //private void ExportDefaultStyles(RadGridView param)
        {
            var grid = param as RadGridView;
            var exportOptions = new GridViewDocumentExportOptions()
            {
                ExportDefaultStyles = true,
                ShowColumnFooters = grid.ShowColumnFooters,
                ShowColumnHeaders = grid.ShowColumnHeaders,
                ShowGroupFooters = grid.ShowGroupFooters
            };
 
            var dialog = new SaveFileDialog()
            {
                DefaultExt = this.SelectedExportFormat,
                Filter = String.Format("(*.{0})|*.{1}", this.SelectedExportFormat, this.SelectedExportFormat)
            };
 
            if (dialog.ShowDialog() == true)
            {
                using (var stream = dialog.OpenFile())
                {
                    switch (this.SelectedExportFormat)
                    {
                        case "xlsx":
                            grid.ExportToXlsx(stream, exportOptions);
                            break;
                        case "pdf":
                            grid.ExportToPdf(stream, exportOptions);
                            break;
                    }
                }
            }
        }

In both methods I'm not correctly figuring out how to set the "grid" correctly so it can be passed down. It works this way in your demo.

Is there any way to download the demo to work on it locally?

10 Answers, 1 is accepted

Sort by
0
Dilyan Traykov
Telerik team
answered on 26 Nov 2020, 01:05 PM

Hello,

Thank you for the provided code snippet.

Can you please clarify what the value of the param property is before the assignment to the grid variable? Providing a screenshot of the output in Visual Studio would be helpful in this case.

Please ensure that the CommandParameter property of the button points to the RadGridView control. You can use an ElementName binding to ensure this.

In the meantime, I've prepared a small sample project based on the demo which you can test out. It works correctly on my machine. As for the code of the demo, you can find it in the Downloads section of your Telerik account. The name of the archive is Telerik_UI_for_WPF_{version}_Demos.zip.

In addition, you can have a look at the examples available in our SDK Samples Browser as well.

I hope you find all of this helpful. Do let me know if you manage to achieve the desired export functionality.

Regards,
Dilyan Traykov
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

0
herb
Top achievements
Rank 1
Veteran
Iron
answered on 26 Nov 2020, 02:46 PM

Thank you Dilyan, I will review this and get back to you.

I would have like to submit my code but no zip files are accepted when posting.

0
herb
Top achievements
Rank 1
Veteran
Iron
answered on 26 Nov 2020, 03:40 PM

Not sure I have what you are looking for here Dilyan,

<Grid DataContext="{StaticResource MyViewModel}">
    <Grid.RowDefinitions>
        <RowDefinition Height="*"/>
        <RowDefinition Height="Auto" />
    </Grid.RowDefinitions>
    <Grid.Resources>
        <DataTemplate x:Key="RowDetailsTemplate">
            <telerik:RadGridView Name="playersGrid"
                                 ItemsSource="{Binding Players}"
                                 AutoGenerateColumns="False">
                <telerik:RadGridView.Columns>
                    <telerik:GridViewDataColumn DataMemberBinding="{Binding Name}"/>
                    <telerik:GridViewDataColumn DataMemberBinding="{Binding Number}"/>
                    <telerik:GridViewDataColumn DataMemberBinding="{Binding Position}"/>
                    <telerik:GridViewDataColumn DataMemberBinding="{Binding Country}"/>
                </telerik:RadGridView.Columns>
            </telerik:RadGridView>
        </DataTemplate>
    </Grid.Resources>
    <telerik:RadGridView Grid.Row="0"
                         Name="clubsGrid"
                         ItemsSource="{Binding Clubs}"
                         AutoGenerateColumns="False"
                         RowDetailsTemplate="{StaticResource RowDetailsTemplate}"
                         Margin="5">
        <telerik:RadGridView.Columns>
            <telerik:GridViewToggleRowDetailsColumn/>
            <telerik:GridViewDataColumn DataMemberBinding="{Binding Name}"/>
            <telerik:GridViewDataColumn DataMemberBinding="{Binding Established}"
                                        Header="Est."
                                        DataFormatString="{}{0:yyyy}"/>
            <telerik:GridViewDataColumn DataMemberBinding="{Binding StadiumCapacity}"
                                        Header="Stadium"
                                        DataFormatString="{}{0:N0}"/>
        </telerik:RadGridView.Columns>
    </telerik:RadGridView>

I found the SDK download. Installed. This looks like old code not as rich as your online DEMO GridView. That would be good code to download and play with. Anyway I hope this helps.

 

0
herb
Top achievements
Rank 1
Veteran
Iron
answered on 26 Nov 2020, 03:42 PM

Here is my full code for "myviewmodel.cs".

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ComponentModel;
using System.Collections.ObjectModel;
//From VMA MrsUserSettingsViewModel.cs
using GalaSoft.MvvmLight;
using GalaSoft.MvvmLight.Command;
using Telerik.Windows.Controls.GridView.SpreadsheetStreamingExport;
//
//From Telerik DEMO GridView Example program
using System.Windows.Input;
using System.Windows.Media;
using System.Windows; //for visiblity
using Telerik.Windows.Controls;
using SaveFileDialog = Microsoft.Win32.SaveFileDialog;
//
 
 
namespace RadGridWithExport
{
    public class MyViewModel : INotifyPropertyChanged
    {
        public event PropertyChangedEventHandler PropertyChanged;
 
        private ObservableCollection<Club> clubs;
        private ObservableCollection<Player> players;
        private object selectedItem;
 
        //From Telerik DEMO GridView Example program
        private ICommand exportCommand = null;
        private ICommand exportDefaultStylesCommand = null;
        private string selectedExportFormat;
 
        public ICommand ExportCommand
        {
            get
            {
                return this.exportCommand;
            }
            set
            {
                if (this.exportCommand != value)
                {
                    this.exportCommand = value;
                    OnPropertyChanged("ExportCommand");
                }
            }
        }
 
        public ICommand ExportDefaultStylesCommand
        {
            get
            {
                return this.exportDefaultStylesCommand;
            }
            set
            {
                if (this.exportDefaultStylesCommand != value)
                {
                    this.exportDefaultStylesCommand = value;
                    OnPropertyChanged("ExportDefaultStylesCommand");
                }
            }
        }
        IEnumerable<string> exportFormats;
        public IEnumerable<string> ExportFormats
        {
            get
            {
                if (exportFormats == null)
                {
                    exportFormats = new string[] { "xlsx", "pdf" };
                }
 
                return exportFormats;
            }
        }
 
        public string SelectedExportFormat
        {
            get
            {
                return selectedExportFormat;
            }
            set
            {
                if (!object.Equals(selectedExportFormat, value))
                {
                    selectedExportFormat = value;
 
                    OnPropertyChanged("SelectedExportFormat");
                }
            }
        }
 
        public MyViewModel()
        {
            this.SelectedExportFormat = this.ExportFormats.FirstOrDefault();
            this.ExportDefaultStylesCommand = new DelegateCommand(this.ExportDefaultStyles);
            this.ExportCommand = new DelegateCommand(this.Export);
        }
        private void Export(object param)
        {
            var grid = param as RadGridView;
            var dialog = new SaveFileDialog()
            {
                DefaultExt = this.SelectedExportFormat,
                Filter = String.Format("(*.{0})|*.{1}", this.SelectedExportFormat, this.SelectedExportFormat)
            };
 
            if (dialog.ShowDialog() == true)
            {
                using (var stream = dialog.OpenFile())
                {
                    switch (this.SelectedExportFormat)
                    {
                        case "xlsx":
                            grid.ExportToXlsx(stream);
                            break;
                        case "pdf":
                            //grid.ExportToPdf(stream);
                            break;
                    }
                }
            }
        }
 
        private void ExportDefaultStyles(object param)
        //private void ExportDefaultStyles(RadGridView param)
        {
            var grid = param as RadGridView;
            var exportOptions = new GridViewDocumentExportOptions()
            {
                ExportDefaultStyles = true,
                ShowColumnFooters = grid.ShowColumnFooters,
                ShowColumnHeaders = grid.ShowColumnHeaders,
                ShowGroupFooters = grid.ShowGroupFooters
            };
 
            var dialog = new SaveFileDialog()
            {
                DefaultExt = this.SelectedExportFormat,
                Filter = String.Format("(*.{0})|*.{1}", this.SelectedExportFormat, this.SelectedExportFormat)
            };
 
            if (dialog.ShowDialog() == true)
            {
                using (var stream = dialog.OpenFile())
                {
                    switch (this.SelectedExportFormat)
                    {
                        case "xlsx":
                            grid.ExportToXlsx(stream, exportOptions);
                            break;
                        case "pdf":
                            grid.ExportToPdf(stream, exportOptions);
                            break;
                    }
                }
            }
        }
 
        //==End of
 
 
        public ObservableCollection<Club> Clubs
        {
            get
            {
                if (this.clubs == null)
                {
                    this.clubs = Club.GetClubs();
                }
 
                return this.clubs;
            }
        }
 
        public ObservableCollection<Player> Players
        {
            get
            {
                if (this.players == null)
                {
                    this.players = Player.GetPlayers();
                }
 
                return this.players;
            }
        }
 
        public object SelectedItem
        {
            get { return this.selectedItem; }
            set
            {
                if (value != this.selectedItem)
                {
                    this.selectedItem = value;
                    this.OnPropertyChanged("SelectedItem");
                }
            }
        }
 
        protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
        {
            PropertyChangedEventHandler handler = this.PropertyChanged;
            if (handler != null)
            {
                handler(this, args);
            }
        }
 
        private void OnPropertyChanged(string propertyName)
        {
            this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
        }
    }
}
0
Dilyan Traykov
Telerik team
answered on 30 Nov 2020, 12:55 PM

Hello,

Thank you for the provided code snippets and images.

It seems like indeed, the MyViewModel is passed as the parameter of the ExportCommand which leads me to believe that the CommandParameter property is either not set or set incorrectly. Can you specify whether the export in the sample project I provided worked as expected?

As I could not observe where you've bound the ExportCommand in your XAML, can you please also share the code for this? Please note that you need to set the CommandParameter as follows, provided you want to export the clubsGrid control:

            <Button Content="Export to XLSX" 
                Command="{Binding ExportCommand}"
                CommandParameter="{Binding ElementName=clubsGrid}" />
Please let me know whether you're able to correctly export the control by applying this modification.

Regards,
Dilyan Traykov
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

0
herb
Top achievements
Rank 1
Veteran
Iron
answered on 30 Nov 2020, 03:13 PM

Entire xaml code:

<Window x:Class="RadGridWithExport.MainWindow"
        xmlns:local="clr-namespace:RadGridWithExport"
        xmlns:my="clr-namespace:RadGridWithExport"
        mc:Ignorable="d"
        Title="MainWindow" Height="700" Width="700">
    <Window.Resources>
        <my:MyViewModel x:Key="MyViewModel"/>
    </Window.Resources>
 
    <Grid DataContext="{StaticResource MyViewModel}">
        <Grid.RowDefinitions>
            <RowDefinition Height="*"/>
            <RowDefinition Height="Auto" />
        </Grid.RowDefinitions>
        <Grid.Resources>
            <DataTemplate x:Key="RowDetailsTemplate">
                <telerik:RadGridView Name="playersGrid"
                                     ItemsSource="{Binding Players}"
                                     AutoGenerateColumns="False">
                    <telerik:RadGridView.Columns>
                        <telerik:GridViewDataColumn DataMemberBinding="{Binding Name}"/>
                        <telerik:GridViewDataColumn DataMemberBinding="{Binding Number}"/>
                        <telerik:GridViewDataColumn DataMemberBinding="{Binding Position}"/>
                        <telerik:GridViewDataColumn DataMemberBinding="{Binding Country}"/>
                    </telerik:RadGridView.Columns>
                </telerik:RadGridView>
            </DataTemplate>
        </Grid.Resources>
        <telerik:RadGridView Grid.Row="0"
                             Name="clubsGrid"
                             ItemsSource="{Binding Clubs}"
                             AutoGenerateColumns="False"
                             RowDetailsTemplate="{StaticResource RowDetailsTemplate}"
                             Margin="5">
            <telerik:RadGridView.Columns>
                <telerik:GridViewToggleRowDetailsColumn/>
                <telerik:GridViewDataColumn DataMemberBinding="{Binding Name}"/>
                <telerik:GridViewDataColumn DataMemberBinding="{Binding Established}"
                                            Header="Est."
                                            DataFormatString="{}{0:yyyy}"/>
                <telerik:GridViewDataColumn DataMemberBinding="{Binding StadiumCapacity}"
                                            Header="Stadium"
                                            DataFormatString="{}{0:N0}"/>
            </telerik:RadGridView.Columns>
        </telerik:RadGridView>
        <StackPanel Grid.Row="1">
            <telerik:RadComboBox Margin="0,10,0,0"
                                 HorizontalContentAlignment="Center"
                                 ItemsSource="{Binding ExportFormats}"
                                 SelectedItem="{Binding SelectedExportFormat, Mode=TwoWay}" />
            <telerik:RadButton Content="Export"
                               Margin="0,35,0,0"
                               Command="{Binding ExportCommand}"
                               CommandParameter="{Binding}" />
            <telerik:RadButton Content="ExportDefaultStyles"
                               Margin="0,10,0,0"
                               Command="{Binding ExportDefaultStylesCommand}"
                               CommandParameter="{Binding}"
                                />
        </StackPanel>
    </Grid>
 
</Window>

Indeed I did not bound. As I'm using an example from a forum posting and the Online Demo.

Entire MyViewModel.cs code:

001.using System;
002.using System.Collections.Generic;
003.using System.Linq;
004.using System.Text;
005.using System.ComponentModel;
006.using System.Collections.ObjectModel;
007.//From VMA MrsUserSettingsViewModel.cs
008.using GalaSoft.MvvmLight;
009.using GalaSoft.MvvmLight.Command;
010.using Telerik.Windows.Controls.GridView.SpreadsheetStreamingExport;
011.//
012.//From Telerik DEMO GridView Example program
013.using System.Windows.Input;
014.using System.Windows.Media;
015.using System.Windows; //for visiblity
016.using Telerik.Windows.Controls;
017.using SaveFileDialog = Microsoft.Win32.SaveFileDialog;
018.//
019. 
020. 
021.namespace RadGridWithExport
022.{
023.    public class MyViewModel : INotifyPropertyChanged
024.    {
025.        public event PropertyChangedEventHandler PropertyChanged;
026. 
027.        private ObservableCollection<Club> clubs;
028.        private ObservableCollection<Player> players;
029.        private object selectedItem;
030. 
031.        //From Telerik DEMO GridView Example program
032.        private ICommand exportCommand = null;
033.        private ICommand exportDefaultStylesCommand = null;
034.        private string selectedExportFormat;
035. 
036.        public ICommand ExportCommand
037.        {
038.            get
039.            {
040.                return this.exportCommand;
041.            }
042.            set
043.            {
044.                if (this.exportCommand != value)
045.                {
046.                    this.exportCommand = value;
047.                    OnPropertyChanged("ExportCommand");
048.                }
049.            }
050.        }
051. 
052.        public ICommand ExportDefaultStylesCommand
053.        {
054.            get
055.            {
056.                return this.exportDefaultStylesCommand;
057.            }
058.            set
059.            {
060.                if (this.exportDefaultStylesCommand != value)
061.                {
062.                    this.exportDefaultStylesCommand = value;
063.                    OnPropertyChanged("ExportDefaultStylesCommand");
064.                }
065.            }
066.        }
067.        IEnumerable<string> exportFormats;
068.        public IEnumerable<string> ExportFormats
069.        {
070.            get
071.            {
072.                if (exportFormats == null)
073.                {
074.                    exportFormats = new string[] { "xlsx", "pdf" };
075.                }
076. 
077.                return exportFormats;
078.            }
079.        }
080. 
081.        public string SelectedExportFormat
082.        {
083.            get
084.            {
085.                return selectedExportFormat;
086.            }
087.            set
088.            {
089.                if (!object.Equals(selectedExportFormat, value))
090.                {
091.                    selectedExportFormat = value;
092. 
093.                    OnPropertyChanged("SelectedExportFormat");
094.                }
095.            }
096.        }
097. 
098.        public MyViewModel()
099.        {
100.            this.SelectedExportFormat = this.ExportFormats.FirstOrDefault();
101.            this.ExportDefaultStylesCommand = new DelegateCommand(this.ExportDefaultStyles);
102.            this.ExportCommand = new DelegateCommand(this.Export);
103.        }
104.        private void Export(object param)
105.        {
106.            var grid = param as RadGridView;
107.            var dialog = new SaveFileDialog()
108.            {
109.                DefaultExt = this.SelectedExportFormat,
110.                Filter = String.Format("(*.{0})|*.{1}", this.SelectedExportFormat, this.SelectedExportFormat)
111.            };
112. 
113.            if (dialog.ShowDialog() == true)
114.            {
115.                using (var stream = dialog.OpenFile())
116.                {
117.                    switch (this.SelectedExportFormat)
118.                    {
119.                        case "xlsx":
120.                            grid.ExportToXlsx(stream);
121.                            break;
122.                        case "pdf":
123.                            //grid.ExportToPdf(stream);
124.                            break;
125.                    }
126.                }
127.            }
128.        }
129. 
130.        private void ExportDefaultStyles(object param)
131.        //private void ExportDefaultStyles(RadGridView param)
132.        {
133.            var grid = param as RadGridView;
134. 
135.            var exportOptions = new GridViewDocumentExportOptions()
136.            {
137.                ExportDefaultStyles = true,
138.                ShowColumnFooters = grid.ShowColumnFooters,
139.                ShowColumnHeaders = grid.ShowColumnHeaders,
140.                ShowGroupFooters = grid.ShowGroupFooters
141.            };
142. 
143.            var dialog = new SaveFileDialog()
144.            {
145.                DefaultExt = this.SelectedExportFormat,
146.                Filter = String.Format("(*.{0})|*.{1}", this.SelectedExportFormat, this.SelectedExportFormat)
147.            };
148. 
149.            if (dialog.ShowDialog() == true)
150.            {
151.                using (var stream = dialog.OpenFile())
152.                {
153.                    switch (this.SelectedExportFormat)
154.                    {
155.                        case "xlsx":
156.                            grid.ExportToXlsx(stream, exportOptions);
157.                            break;
158.                        case "pdf":
159.                            grid.ExportToPdf(stream, exportOptions);
160.                            break;
161.                    }
162.                }
163.            }
164.        }
165. 
166.        //==End of
167. 
168. 
169.        public ObservableCollection<Club> Clubs
170.        {
171.            get
172.            {
173.                if (this.clubs == null)
174.                {
175.                    this.clubs = Club.GetClubs();
176.                }
177. 
178.                return this.clubs;
179.            }
180.        }
181. 
182.        public ObservableCollection<Player> Players
183.        {
184.            get
185.            {
186.                if (this.players == null)
187.                {
188.                    this.players = Player.GetPlayers();
189.                }
190. 
191.                return this.players;
192.            }
193.        }
194. 
195.        public object SelectedItem
196.        {
197.            get { return this.selectedItem; }
198.            set
199.            {
200.                if (value != this.selectedItem)
201.                {
202.                    this.selectedItem = value;
203.                    this.OnPropertyChanged("SelectedItem");
204.                }
205.            }
206.        }
207. 
208.        protected virtual void OnPropertyChanged(PropertyChangedEventArgs args)
209.        {
210.            PropertyChangedEventHandler handler = this.PropertyChanged;
211.            if (handler != null)
212.            {
213.                handler(this, args);
214.            }
215.        }
216. 
217.        private void OnPropertyChanged(string propertyName)
218.        {
219.            this.OnPropertyChanged(new PropertyChangedEventArgs(propertyName));
220.        }
221. 
222. 
223. 
224.        //!!!!!!!!!!!!!!!!!!!!!!!!!!   
225.    }
226.}

 

 

0
herb
Top achievements
Rank 1
Veteran
Iron
answered on 30 Nov 2020, 03:31 PM

I've attached the Telerik Demo screen shot for which I want to build locally. The excel output created by the demo looks like an excel "grouping" (see Excel output screenshot.jpg).

I modified my code to correct my lack of "binding element...." and it now will export to excel. but missing the richness found in the Telerik code.

Not sure how to get to the same output as in the "Telerik Grid View | exporting to xlsx and pdf"?

0
Accepted
Dilyan Traykov
Telerik team
answered on 01 Dec 2020, 01:52 PM

Hello,

Thank you for the provided images and code snippets.

I've further modified the sample project to mimic the demo by setting the ShowGroupFootersShowColumnFooters, and AutoExpandGroups properties to True and also including a default GroupDescriptor. Using these settings, the grouping functionality is enabled in Excel at my end.

Can you please have a look and let me know if this provides the desired result?

Regards,
Dilyan Traykov
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

0
herb
Top achievements
Rank 1
Veteran
Iron
answered on 01 Dec 2020, 03:32 PM

Dilyan,

Yes this is want I'm looking for. Thank you very much for your patience and help on this post.

I will work on this to understand how it work so I can implement something like this in my project.

 

0
Dilyan Traykov
Telerik team
answered on 02 Dec 2020, 02:01 PM

Hello,

I'm happy to hear that the sample project demonstrates the desired result. Do let me know if you require any further assistance with implementing this in your actual project.

Regards,
Dilyan Traykov
Progress Telerik

Virtual Classroom, the free self-paced technical training that gets you up to speed with Telerik and Kendo UI products quickly just got a fresh new look + new and improved content including a brand new Blazor course! Check it out at https://learn.telerik.com/.

Tags
GridView
Asked by
herb
Top achievements
Rank 1
Veteran
Iron
Answers by
Dilyan Traykov
Telerik team
herb
Top achievements
Rank 1
Veteran
Iron
Share this question
or