Export Gridview to Excel in a web application

Hope you guys can help me. I have tried many different things and cannot make it work.

I have a gridview as shown in the update panel below:

<asp:UpdatePanel ID="udpReport" runat="server" UpdateMode="Conditional" ChildrenAsTriggers="true">
      <ContentTemplate>
          <asp:GridView runat="server" ID="preferenceReportGrd" AutoGenerateColumns="false"
               AutoGenerateSelectButton="false" CaptionAlign="Top" EnableSortingAndPagingCallbacks="false" HorizontalAlign="left" CssSelectorClass="gvwPrefReport">
                   <Columns>
                       <asp:BoundField ReadOnly="true" DataField="ClientName" HeaderText="Company Name" />
                            <asp:BoundField ReadOnly="true" DataField="typeDescription" HeaderText="Preference" />
                            <asp:BoundField ReadOnly="true" DataField="defaultValue" HeaderText="Default Preference" />
                            <asp:BoundField ReadOnly="true" DataField="previousPreferenceValue" HeaderText="Previous Preference" />
                            <asp:BoundField ReadOnly="true" DataField="selectedValue" HeaderText="New Preference" />
                            <asp:BoundField ReadOnly="true" DataField="lastUpdated" HeaderText="Date Last Edited" />
                    </Columns>
          </asp:GridView>
          <div>
              <user:MsgLine runat="server" ID="MsgLine1" />
          </div>
     </ContentTemplate>
</asp:UpdatePanel>

I am trying to export this gridview to excel. There is a button that the user clicks on it, calls the on_click method for that button, and in this on_click I have the following:

        string attachment = "attachment; filename=Employee.xls";            
        Response.AddHeader("content-disposition", attachment);
        Response.ContentType = "application/excel";
        StringWriter stw = new StringWriter();
        HtmlTextWriter htextw = new HtmlTextWriter(stw);
        preferenceReportGrd.RenderControl(htextw);
        Response.Write(stw.ToString());
        Response.End();

I get nothing from this verified debugging, it seems that when I smoke over stw.tostring (), all the values ​​for gridview are there, but nothing is written out.

+3
source share
4 answers

. excel export . . ,

</ContentTemplate>          
       <Triggers>
        <asp:PostBackTrigger ControlID="BtnExport" />
    </Triggers>
        </asp:UpdatePanel>

+3

GridView / async, , . , . , ...

...
1. c-sharpcorner
2.
3.

+2

PostBackTrigger .

Excel 2003

Response.ContentType = "application/vnd.ms-excel

Excel 2007

Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"

.

: : PostBackTrigger , , , , GridView.

EDIT EDIT: ----- - , Extension Hardening, Excel 2007. fooobar.com/questions/281035/... ; , .

+1

, , gridview gridview , ( ). Excel , .

, , , , .

, , , , . , .

0

Source: https://habr.com/ru/post/1710175/


All Articles