简体   繁体   中英

Export to excel in C# error

I am trying to export my panel into excel using this code.

Design :

<asp:Panel ID="ExcelPanel" runat="server" Visible="false">
    <asp:GridView ID="ExcelGridView" runat="server" AutoGenerateColumns="False" 
    Width="100%" CellPadding="3" ForeColor="#333333" GridLines="Both" ShowHeader="True" Visible="true" >   
        <Columns>
            <asp:TemplateField HeaderText="S. No." HeaderStyle-CssClass="gridViewHeader" ItemStyle-HorizontalAlign="left" SortExpression="wcName"  ItemStyle-Width="12%">
                <ItemTemplate>
                    <asp:Label ID="performanceReportTBMWCNameLabel" runat="server" Text='<%# Eval("SNo") %>' CssClass="gridViewItems"></asp:Label>
                </ItemTemplate>
            </asp:TemplateField>
        </Columns>
    </asp:GridView>
</asp:Panel>

C# Code :

ExcelGridView.DataSource = gridviewdt;
ExcelGridView.DataBind();
ExcelPanel.Visible = true;
Response.Clear();
Response.ClearHeaders();
Response.ClearContent();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=file.xls");
Response.ContentType = "application/vnd.ms-excel";

StringWriter stringWrite = new StringWriter();
HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
ExcelPanel.RenderControl(htmlWrite);

Response.Write(stringWrite.ToString());

Response.Flush();
Response.End();
ExcelPanel.Visible = false;

This is the area I want to be in my excel file. But I am getting the whole page with master page as well in the excel file. How can I avoid whole page and only get the panel in the excel file?

You are Rendering HTML from ExcelPanel hence it is showing All HTML regarding to That panel change panel to GridView so it will fetch HTML from GridView

change

ExcelPanel.RenderControl(htmlWrite);

to

ExcelGridView.RenderControl(htmlWrite);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM