从GridView到Excel的导出数据问题

时间:2014-04-22 17:06:30

标签: c# asp.net gridview

我尝试使用下一个源将我的gridView导出为ex​​cel:

protected void btn_ExportExcel_Click(object sender, EventArgs e)
    {
        try
        {
           string filename = String.Format("Results_{0}_{1}.xls", DateTime.Today.Month.ToString(), DateTime.Today.Year.ToString());
            if (!string.IsNullOrEmpty(grid_dadosEntidades.Page.Title))
                filename = grid_dadosEntidades.Page.Title + ".xls";
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=" + filename);
            Response.ContentType = "application/vnd.xls";
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
            grid_dadosEntidades.RenderControl(htmlWrite);
            Response.Write(stringWrite.ToString());
            Response.End();
            HttpContext.Current.ApplicationInstance.CompleteRequest();

        }
        catch (Exception ex)
        {
            throw;
        }
    }

    public override void VerifyRenderingInServerForm(Control control)
    {
        /* Verifies that the control is rendered */
    }

我使用的是框架4.0,而我的GridView是:

<div class="TableBlock1">
                <asp:GridView ID="grid_dadosEntidades" runat="server" AllowPaging="True" AllowSorting="True"
                    AutoGenerateColumns="False" DataKeyNames="CodSeguradora_PK" OnPageIndexChanging="grid_dadosEntidades_PageIndexChanging"
                    OnSorting="grid_dadosEntidades_Sorting" OnRowCommand="grid_dadosEntidades_RowCommand"
                    OnRowDataBound="grid_dadosEntidades_RowDataBound" Width="820px" ViewStateMode="Enabled"
                    EmptyDataText="Não existem registos a mostrar." ShowHeaderWhenEmpty="True">
                    <Columns>
                        <asp:TemplateField HeaderStyle-CssClass="hidden" ItemStyle-CssClass="hidden">
                            <ItemTemplate>
                                <asp:Button runat="server" ID="SelectButton" CommandName="Select" />
                            </ItemTemplate>
                            <HeaderStyle CssClass="hidden" />
                            <ItemStyle CssClass="hidden" />
                        </asp:TemplateField>
                        <asp:TemplateField ShowHeader="False">
                            <ItemTemplate>
                                <asp:RadioButton ID="rb_Grid" runat="server" />
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField DataField="CodEstatistico" HeaderText="Código" ReadOnly="True" SortExpression="CodEstatistico" />
                        <asp:BoundField DataField="NomSocial" HeaderText="Denominação Social" ReadOnly="True"
                            SortExpression="NomSocial" />
                        <asp:BoundField DataField="DtInicioActividade" HeaderText="Início Atividade" SortExpression="DtInicioActividade"
                            DataFormatString="{0:dd/MM/yyyy}" ItemStyle-Wrap="false" />
                        <asp:BoundField DataField="DtEncerramento" HeaderText="Encerramento" SortExpression="DtEncerramento"
                            DataFormatString="{0:dd/MM/yyyy}" ItemStyle-Wrap="false" />
                    </Columns>
                    <SortedAscendingHeaderStyle CssClass="sortasc" />
                    <SortedDescendingHeaderStyle CssClass="sortdesc" />
                </asp:GridView>
            </div>

问题是,当我尝试打开excel文件时,只显示网格中的一些数据,因为我在网格视图上有OnPageIndexChanging

3 个答案:

答案 0 :(得分:1)

我建议您至少下载Open XML SDK 2.0 Productivity Tool。我可以通过单击“验证”按钮向您显示错误:

Validate

打开XML SDK工具:

http://www.microsoft.com/en-us/download/details.aspx?id=5124

答案 1 :(得分:1)

试试这个link

提到它会关闭网格的分页然后导出。

GridView1.AllowPaging = false;
GridView1.DataBind();

然后它将为您提供所有数据。

答案 2 :(得分:0)

这段代码对我有用。请试试。

var grid = new System.Web.UI.WebControls.GridView();
IQueryable<Customer> result = _db.Customers;
var dataToExport = from b in result.AsEnumerable()
                               select new
                                   {                                       
                                       b.CustomerContactName,
                                       b.CustomerContactNo,
                                       b.CustomerContactEmail
                                   };
grid.DataSource = dataToExport.ToList();
grid.DataBind();

Response.ClearContent();
Response.AddHeader("content-disposition", "attachment; filename=FileName.xls");
Response.ContentType = "application/excel";
var sw = new StringWriter();
var htw = new HtmlTextWriter(sw);

grid.RenderControl(htw);
Response.Write(sw.ToString());
Response.End();