Click here to Skip to main content
15,879,474 members
Please Sign up or sign in to vote.
1.00/5 (1 vote)
See more:
Hi,

I am trying to export data from telerik Radgrid to csv.
this is working on other pages, and the excel starts downloading upon click of asp linkbutton
but in one of my page the Radgrid have the filters.

I am trying to Export the data from this radgrid to CSV but excel doesn't appear.
Checked in debug mode the code runs fine without error just the excel is not opened.

I am not sure what this error and why the excel is not getting generated when i go through Item command options.
is it because the grid have filter?
Any help is appreciated
Thanks in advance.

Here is the code of my aspx page
VB
<pre><%@ Page Language="VB" MasterPageFile="~/Admin/Default.master" AutoEventWireup="false" CodeFile="ClientCase.aspx.vb" Inherits="Admin_ClientCase" %>

<%@ Register TagPrefix="telerik" Namespace="Telerik.Web.UI" Assembly="Telerik.Web.UI" %>
<asp:Content ID="Content1" ContentPlaceHolderID="head" runat="Server">
</asp:Content>
<asp:Content ID="Content2" ContentPlaceHolderID="ContentPlaceHolder1" runat="Server">
    <telerik:RadAjaxLoadingPanel ID="RadAjaxLoadingPanel1" runat="server">
    </telerik:RadAjaxLoadingPanel>
    <telerik:RadAjaxManagerProxy ID="RadAjaxManager1" runat="server">
        <AjaxSettings>
            <telerik:AjaxSetting AjaxControlID="RadClients">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="RadClients" LoadingPanelID="RadAjaxLoadingPanel1" />
                </UpdatedControls>
            </telerik:AjaxSetting>
            <telerik:AjaxSetting AjaxControlID="CmbDays">
                <UpdatedControls>
                    <telerik:AjaxUpdatedControl ControlID="RadClients" LoadingPanelID="RadAjaxLoadingPanel1" />
                    <telerik:AjaxUpdatedControl ControlID="LtrCasesno" LoadingPanelID="RadAjaxLoadingPanel1" />
                </UpdatedControls>
            </telerik:AjaxSetting>
        </AjaxSettings>
    </telerik:RadAjaxManagerProxy>
    <div class="processteamtabs clearfix">
        <h1>
            Manage Cases</h1>
        <div class="casesentered">
            <label>
                <asp:Literal ID="LtrCasesno" runat="server"></asp:Literal>
            </label>
            <fieldset>
                <asp:DropDownList ID="CmbDays" runat="server" AutoPostBack="true">
                    <asp:ListItem Text="Today" Value="0"></asp:ListItem>
                    <asp:ListItem Text="Last 2 days"    Value="2"></asp:ListItem>
                    <asp:ListItem Text="Last 4 days"    Value="4"></asp:ListItem>
                    <asp:ListItem Text="Last 1 week"   Value="7"></asp:ListItem>
                    <asp:ListItem Text="Last 2 weeks" Value="14"></asp:ListItem>
                    <asp:ListItem Text="Last 1 month" Value="31"></asp:ListItem>
                    <asp:ListItem Text="Last 2 month" Value="61"></asp:ListItem>
                    <asp:ListItem Text="Last 3 month" Value="92"></asp:ListItem>
                </asp:DropDownList>
            </fieldset>
        </div>
        <div class="tabsformatprocess clearfix">
            <div class="tabcontents tabcontentsanother">
                <div id="Div1" style="display: block;" class="Clients-info">
                    <table width="100%" border="0" cellspacing="0" cellpadding="0" class="paginationtable">
                        <tr>
                            <td width="70%"> <asp:Literal ID="ErrorMsg" runat="server"></asp:Literal></td>
                            <td width="6%">Assign To:
                            </td>
                            <td width="20%">
                                <asp:DropDownList ID="CmbAssignTo" runat="server">
                                    <asp:ListItem value="0" Text="--Select--"></asp:ListItem>
                                </asp:DropDownList>
                                <asp:RequiredFieldValidator ID="RequiredFieldValidator9" runat="server" ControlToValidate="CmbAssignTo"
                                    InitialValue="0" Display="Dynamic" SetFocusOnError="true" ValidationGroup="Assign"
                                    ErrorMessage="<div class='formError impalert'><div class='formErrorContent'>* This field is required<br />* PLEASE SELECT.<br /></div><div class='formErrorArrow'><div class='line10'><!-- --></div><div class='line9'><!-- --></div><div class='line8'><!-- --></div><div class='line7'><!-- --></div><div class='line6'><!-- --></div><div class='line5'><!-- --></div><div class='line4'><!-- --></div><div class='line3'><!-- --></div><div class='line2'><!-- --></div><div class='line1'><!-- --></div></div></div>"></asp:RequiredFieldValidator>
                            </td>
                            <td width="4%">
                                <asp:Button ID="BtnAssign" runat="server" Text="Assign" CssClass="buttonformat" ValidationGroup="Assign" />
                            </td>
                        </tr>
                        <tr>
                            <td colspan="4"> 
                            </td>
                        </tr>
                    </table>
                    <telerik:RadGrid ID="RadClients" ShowGroupPanel="false" runat="server" GridLines="None"
                        AllowPaging="true" AllowSorting="True" AllowFilteringByColumn="true" AutoGenerateColumns="False"
                        AllowMultiRowSelection="true" CssClass="contactfoundbox manage-com" PageSize="50">
                        <GroupingSettings CaseSensitive="false" />
                        <PagerStyle Mode="NextPrevNumericAndAdvanced" AlwaysVisible="true" />
                        <MasterTableView GridLines="None" Width="100%" CommandItemDisplay="Top" DataKeyNames="Case_ref_no"
                            GroupLoadMode="Client" GroupsDefaultExpanded="false">
                            <CommandItemTemplate>
                                <asp:LinkButton ID="link" runat="server" CommandName="RebindGrid"><img style="border:0px" alt="" src="../Skins/Outlook/Grid/Refresh.gif" />  Refresh</asp:LinkButton>
                                <asp:LinkButton ID="lnkExport" runat="server" CommandName="ExportGrid" ClientIDMode="Static">
                                   <img style="border:0px;vertical-align:middle;width:18px;" alt="" src="<%#ResolveUrl("~/Admin/images/Excel-xls.ico")%>"/>Export</asp:LinkButton>
                            </CommandItemTemplate>
                            <Columns>
                              <telerik:GridTemplateColumn UniqueName="TemplateColumn" Groupable="false" AllowFiltering="false"
                                    HeaderText="Select" Exportable="false">
                                    <HeaderTemplate>
                                        <asp:CheckBox ID="headerChkbox"  OnCheckedChanged="ToggleSelectedState" AutoPostBack="true"
                                            runat="server"></asp:CheckBox>
                                    </HeaderTemplate>
                                    <ItemTemplate>
                                        <asp:CheckBox runat="server" ID="View" />
                                    </ItemTemplate>
                                </telerik:GridTemplateColumn>
                                <telerik:GridBoundColumn DataField="caserefno" HeaderText="Case Ref. #" SortExpression="caserefno"
                                    UniqueName="caserefno" FilterControlWidth="200px" ItemStyle-Width="250px">
                                </telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="ClientName" HeaderText="Client Name/ Location"
                                    SortExpression="ClientName" UniqueName="ClientName" FilterControlWidth="200px"
                                    ItemStyle-Width="250px">
                                </telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="Candidate" HeaderText="Candidate Name" SortExpression="Candidate"
                                    UniqueName="Candidate" FilterControlWidth="200px" ItemStyle-Width="250px">
                                </telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="Case_In_Date" HeaderText="Case Received Date" SortExpression="Case_In_Date"
                                    UniqueName="Case_In_Date" DataFormatString="{0:dd-MM-yyyy}">
                                </telerik:GridBoundColumn>
                                 <telerik:GridBoundColumn DataField="Created_on" HeaderText="Case In Date" SortExpression="Created_on"
                                    UniqueName="Created_on" DataFormatString="{0:dd-MM-yyyy}">
                                </telerik:GridBoundColumn>
                                <telerik:GridBoundColumn DataField="IsActive" HeaderText="Status" SortExpression="IsActive"
                                    UniqueName="IsActive">
                                    <FilterTemplate>
                                        <telerik:RadComboBox ID="FuelCombo" Width="90px" SelectedValue='<%# CType(Container, GridItem).OwnerTableView.GetColumn("IsActive").CurrentFilterValue %>'
                                            runat="server" OnClientSelectedIndexChanged="IsActiveIndexChanged">
                                            <Items>
                                                <telerik:RadComboBoxItem Text="All" Value="" />
                                                <telerik:RadComboBoxItem Text="Active" Value="Active" />
                                                <telerik:RadComboBoxItem Text="Inactive" Value="Inactive" />
                                            </Items>
                                        </telerik:RadComboBox>
                                        <telerik:RadScriptBlock ID="RadScriptBlock4" runat="server">
                                            <script type="text/javascript">
                                                function IsActiveIndexChanged(sender, args) {
                                                    var tableView = $find("<%# CType(Container, GridItem).OwnerTableView.ClientID %>");
                                                                                                                                                                                                                                                                                                                                                                                tableView.filter("IsActive", args.get_item().get_value(), "EqualTo");
                                                }
                                            </script>
                                        </telerik:RadScriptBlock>
                                    </FilterTemplate>
                                </telerik:GridBoundColumn>
                            </Columns>
                            <ExpandCollapseColumn Visible="False">
                                <HeaderStyle Width="19px" />
                            </ExpandCollapseColumn>
                            <RowIndicatorColumn Visible="False">
                                <HeaderStyle Width="20px" />
                            </RowIndicatorColumn>
                        </MasterTableView>
                        <ClientSettings AllowGroupExpandCollapse="True" ReorderColumnsOnClient="True" AllowDragToGroup="false"
                            AllowColumnsReorder="True" Selecting-AllowRowSelect="true">
                        </ClientSettings>
                    </telerik:RadGrid>
                </div>
            </div>
        </div>
    </div>
    <input id="TxtID" runat="server" type="hidden" />
    <asp:LinkButton ID="Lnk" runat="server" Text="G0" Style="left: -450px; position: relative"></asp:LinkButton>
    <telerik:RadCodeBlock ID="RadCodeBlock1" runat="server">
        <script type="text/javascript">
            function editcase(edid) {
                document.getElementById("<%=TxtID.ClientID %>").value = edid;
                __doPostBack('<%=Lnk.UniqueID%>', '');
            }
        </script>
    </telerik:RadCodeBlock>
</asp:Content>


and code behind page
VB.NET
Imports CommonClasses
Imports Sql
Imports Telerik.Web.UI
Imports System.Data
Partial Class Admin_ClientCase
    Inherits System.Web.UI.Page
    Protected Sub Page_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        If Not IsPostBack Then
            Fill_ComboBox(CmbAssignTo, "Exec GetDataEntryMember")
            If Request.QueryString("ID") IsNot Nothing Then
                Dim intid As Integer = Request.QueryString("ID")
                Response.Clear()
                Dim Sb As String = GET_RedirectForm("case-details.aspx", "CaseID", intid.ToString())
                Response.Write(Sb.ToString())
                Response.End()
            End If
        End If

    End Sub


    Protected Sub BtnAssign_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles BtnAssign.Click

        Dim Strsql As New StringBuilder()
        Dim i As Integer = 0
        For Each grdItem As GridDataItem In RadClients.Items
            Dim chkView As CheckBox = DirectCast(grdItem.FindControl("View"), CheckBox)
            If chkView.Checked Then
                
                Dim intcaseid As Integer = grdItem.OwnerTableView.DataKeyValues(grdItem.ItemIndex)("Case_ref_no")
                Strsql.Append("Update  mst_case set Created_by=" & CmbAssignTo.SelectedItem.Value)
                Strsql.Append(",modified_by=" & Request.Cookies("UserInfo").Values("Uid") & ",Modified_on=GETDATE() where Case_ref_no" & "=" & intcaseid & "; ")

                Strsql.Append("Exec Add_CaseLog " & intcaseid & ", " & 0 & ", 0, 'Assign to DETM Member' ")
                Strsql.Append(",'Client Case Assign to   (" & CmbAssignTo.SelectedItem.Text & ")'," & Request.Cookies("UserInfo").Values("Uid") & ";")
                i += 1
            End If
        Next

        If i > 0 Then
            Insert_Update_Delete_Record(Strsql.ToString())
        End If
        RadClients.Rebind()
        ErrorMsg.Text = "Assign  successfully"
    End Sub

    Protected Sub RadClients_ItemCommand(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridCommandEventArgs) Handles RadClients.ItemCommand
        If e.CommandName = Telerik.Web.UI.RadGrid.RebindGridCommandName Then
            For Each column As GridColumn In RadClients.MasterTableView.Columns
                column.CurrentFilterFunction = GridKnownFunction.NoFilter
                column.CurrentFilterValue = String.Empty
            Next
            RadClients.MasterTableView.FilterExpression = String.Empty
            RadClients.MasterTableView.Rebind()
        End If
        If e.CommandName = "ExportGrid" Then
                Export()
            End If
    End Sub

    Private Sub Export()
        Try
            RadClients.ExportSettings.FileName = "Testfile"
            RadClients.MasterTableView.GetColumn("TemplateEditColumn").Visible = False
            'RadClients.ExportSettings.Excel.Format = DirectCast([Enum].Parse(GetType(GridExcelExportFormat), "ExcelML"), GridExcelExportFormat)
            RadClients.ExportSettings.IgnorePaging = False
            RadClients.ExportSettings.ExportOnlyData = True
            RadClients.ExportSettings.OpenInNewWindow = False
            RadClients.MasterTableView.Rebind()
            RadClients.MasterTableView.ExportToCSV()
            RadClients.MasterTableView.GetColumn("TemplateEditColumn").Visible = True
        Catch ex As Exception

        End Try
    End Sub


    Protected Sub ToggleSelectedState(ByVal sender As Object, ByVal e As EventArgs)
        If (CType(sender, CheckBox)).Checked Then
            For Each dataItem As GridDataItem In RadClients.MasterTableView.Items
                CType(dataItem.FindControl("View"), CheckBox).Checked = True
                dataItem.Selected = True
            Next
        Else
            For Each dataItem As GridDataItem In RadClients.MasterTableView.Items
                CType(dataItem.FindControl("View"), CheckBox).Checked = False
                dataItem.Selected = False
            Next
        End If
    End Sub


    Protected Sub RadClients_NeedDataSource(ByVal sender As Object, ByVal e As Telerik.Web.UI.GridNeedDataSourceEventArgs) Handles RadClients.NeedDataSource
        If Request.QueryString("ID") Is Nothing Then
            Dim dtfrom As New DateTime()
            Dim dtto As New DateTime()
            dtto = Now.Date()

            If CmbDays.SelectedValue > 0 Then
                dtfrom = dtto.AddDays((CmbDays.SelectedValue * -1))
            Else
                dtfrom = dtto
            End If
            Dim dt As New DataTable
            dt = Fill_Table("Exec Sp_GetAllNewClientCase '" & Format(dtfrom, "dd-MM-yyyy") & "','" & Format(dtto, "dd-MM-yyyy") & "'")
            RadClients.DataSource = dt
            LtrCasesno.Text = dt.Rows.Count & " case(s) entered :"
        End If
    End Sub

    Protected Sub CmbDays_SelectedIndexChanged(ByVal sender As Object, ByVal e As System.EventArgs) Handles CmbDays.SelectedIndexChanged
        RadClients.Rebind()
    End Sub

    Protected Sub Lnk_Click(ByVal sender As Object, ByVal e As System.EventArgs) Handles Lnk.Click
        If IsNumeric(TxtID.Value) Then
            Dim intid As Integer = TxtID.Value

            Response.Clear()
            Dim Sb As String = GET_RedirectForm("case-details.aspx", "CaseID", intid.ToString(), "editcase")
            Response.Write(Sb.ToString())
            Response.End()
        End If
    End Sub
End Class


What I have tried:

I have tried the same code outside the grid on a button click it works flawlessly and gives excel output
Posted
Updated 23-Nov-21 0:18am
v2

1 solution

Quote:
I am trying to Export the data from this radgrid to CSV but excel doesn't appear.
Checked in debug mode the code runs fine without error just the excel is not opened.


CSV is not an Excel file (OpenXML format). CSV is comma separated text file. Even, if you can open csv file in Excel, it does NOT mean, that CSV is an Excel file. It does NOT mean that CSV file can be opened in Excel by default.

I'd suggest to read this: Telerik Web Forms CSV Export - RadGrid | Telerik UI for ASP.NET AJAX[^]

On the other hand - we can't help as long as you don't share your code.
 
Share this answer
 
Comments
Sonal Ayare 23-Nov-21 8:35am    
Even exporttoexcel() is not generating the result in excel

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900