65.9K
CodeProject is changing. Read more.
Home

Save a Telerik Grid to Excel with Filtering

starIconstarIconstarIconstarIcon
emptyStarIcon
starIcon

4.67/5 (2 votes)

May 20, 2014

CPOL
viewsIcon

10313

How to save a Silverlight Telerik grid content to Excel

Introduction

This is a quick function to allow you to export a Telerik datagrid content to Excel with the option to use or ignore the on-screen filtering applied.

using System;
using System.Net;
using System.Windows;
using System.Windows.Controls;
using System.IO;
using Telerik.Windows.Controls;

using System.Linq;
using System.Collections.Generic;

namespace HFAdminCentral2011
{
    /// <summary>
    /// Single global class to take care of Excel export related functionality 
    /// </summary>
    public static class ExcelUtilities
    {
        /// <summary>
        /// Exports the grid passed in to the given filename, as an Excel file
        /// </summary>
        /// <param name="gridToexport" />
        /// The telerik datagrid that is the source of the data
        /// 
        /// <param name="filename" />
        /// The full path filename to save the file as (this can be changed by the user)
        /// 
        /// <param name="exportAsFiltered" />
        /// If true, export as filtered on screen - otherwise export all underlying data
        /// 
        public static void ExportTelerikGridToExcel
                      (Telerik.Windows.Controls.RadGridView gridToexport,
            string filename,
            bool exportAsFiltered)
        {
            string extension = "xls";
                SaveFileDialog dialog = new SaveFileDialog()
                {
                    DefaultFileName = filename ,
                    DefaultExt = extension,
                    Filter = String.Format("{1} files (*.{0})|*.{0}|All files (*.*)|*.*", 
                             extension, "Excel"),
                    FilterIndex = 1
                };
                if (dialog.ShowDialog() == true)
                {
                    using (Stream stream = dialog.OpenFile())
                    {
                        GridViewExportOptions options = new GridViewExportOptions()
                            {
                                Format = ExportFormat.ExcelML,
                                ShowColumnHeaders = true,
                                ShowColumnFooters = false,
                                ShowGroupFooters = false
                            };

                        if (exportAsFiltered)
                        {
                            options.Items = 
                               ((System.Collections.IEnumerable)gridToexport.Items);
                        }

                        gridToexport.Export(stream,
                         options);
                    }
                }
        }
    }
}

History

  • 20th May, 2014: Initial version