从gridview asp.net导出到excel

本文关键字:excel net gridview asp | 更新日期: 2023-09-27 18:27:20

我阅读了许多关于stackoverflowcode project的文章,并将其实现到我的代码和页面中。但我无法将网格视图数据导出到excel。我正在将我的gridview与页面上的object datasource绑定。但没有成功出口到卓越。你能告诉我我做错了什么吗。下面是我给出的所有代码流。

<%@ Page Language="C#" Theme="Default" MasterPageFile="~/Order/Order.master" AutoEventWireup="true" CodeFile="ActiveOrders.aspx.cs" Inherits="ActiveOrders" Title="SimplyDispatch-ActiveOrders List" EnableEventValidation="false" %>  

<data:EntityGridView ID="GridView1" runat="server" AutoGenerateColumns="False" OnSelectedIndexChanged="GridView1_SelectedIndexChanged"
 DataSourceID="ActiveOrdersDataSource" Width="100%" DataKeyNames="OrderNo" AllowMultiColumnSorting="false"                                         DefaultSortColumnName="OrderNo" OnRowCommand="GridView1_RowCommond" OnRowDataBound="GridView1_OnRowDataBound"                                          AllowSorting="true" DefaultSortDirection="Descending"                                         PageSize="50"  EnableViewState="true" >
    <Columns>
     <asp:BoundField DataField="OrderNo" HeaderStyle-HorizontalAlign="Right" ItemStyle-HorizontalAlign="Right"                                            HeaderText="Order No" SortExpression="[OrderNo]" />
      <asp:BoundField DataField="OrderDate" HeaderStyle-HorizontalAlign="Center" ItemStyle-HorizontalAlign="Center"                                               DataFormatString="{0:d}" HtmlEncode="False" HeaderText="Order Date" SortExpression="[OrderDate]" />
    </Columns>                 
     <EmptyDataTemplate>
   </EmptyDataTemplate>
    </data:EntityGridView>

网格视图数据源

 <data:ActiveOrdersDataSource ID="ActiveOrdersDataSource" runat="server" SelectMethod="GetPaged" EnablePaging="True" EnableSorting="True" EnableDeepLoad="True">
</data:ActiveOrdersDataSource>

我要导出到excel的代码低于

 protected void ExportToExcel(object sender, EventArgs e)
    {
        try
        {
 Response.Clear();
            Response.ClearHeaders();
            Response.Buffer = true;
            Response.AddHeader("content-disposition", "attachment;filename=" + "Excelsheet_" + DateTime.Now.Ticks.ToString() + ".xls");
            Response.Charset = "";
            Response.ContentType = "application/vnd.xls";
            StringWriter StringWriter = new System.IO.StringWriter();
            HtmlTextWriter HtmlTextWriter = new HtmlTextWriter(StringWriter);
            GridView1.AllowSorting = false;
            GridView1.RenderControl(HtmlTextWriter);// render gridview control
            Response.Write(StringWriter.ToString());
            Response.End();
        }
        catch (Exception ex)
        {
        }
    }
public override void VerifyRenderingInServerForm(Control control)
    {
        /* Confirms that an HtmlForm control is rendered for the specified ASP.NET
           server control at run time. */
    }

从gridview asp.net导出到excel

将EnableEventValidation设置为True,然后重试。或者使用closedXML,这是导出到excel的最简单方法之一,也很有效。https://closedxml.codeplex.com/

将数据表保存在会话中,并将数据表传递给以下方法,以执行导出功能。

 public  void ExportToExcel(DataTable dt)
{
    XLWorkbook wb = new XLWorkbook();
    //Specify sheet name
    var ws = wb.Worksheets.Add(dt, "SHEET NAME");
    ws.Columns().AdjustToContents();
    ws.Style.Fill.BackgroundColor = XLColor.Transparent;
    var excelTable = ws.Tables.First();
    excelTable.ShowAutoFilter = false;
    excelTable.ShowRowStripes = false;
    excelTable.Theme = XLTableTheme.None;
    excelTable.Style.Border.TopBorder = XLBorderStyleValues.Thin;
    excelTable.Style.Border.BottomBorder = XLBorderStyleValues.Thin;
    excelTable.Style.Border.RightBorder = XLBorderStyleValues.Thin;
    excelTable.Style.Border.LeftBorder = XLBorderStyleValues.Thin;
    var headerRow = ws.Tables.First().FirstRow();
    headerRow.Style.Fill.BackgroundColor = XLColor.Transparent;
    headerRow.Style.Font.Bold = true;
//specify filename
    string fileName = "File Name"  + ".xlsx";
    HttpResponse httpResponse = Response;
    httpResponse.Clear();
    httpResponse.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet";
    httpResponse.AddHeader("content-disposition", "attachment;filename='"" + fileName + "'"");
    // Flush the workbook to the Response.OutputStream
    using (MemoryStream memoryStream = new MemoryStream())
    {
        wb.SaveAs(memoryStream);
        memoryStream.WriteTo(httpResponse.OutputStream);
        memoryStream.Close();
    }
    httpResponse.End();
}

尝试此代码

protected void ExportToExcel(object sender, EventArgs e)
    {
      try
      {
        Response.ClearContent();
        Response.ClearHeaders();
        Response.AddHeader("contentdisposition","attachment;filename=Demo.xls");
        Response.ContentType = "application/ms-excel";
        Response.ContentEncoding = System.Text.Encoding.Unicode;
        Response.BinaryWrite(System.Text.Encoding.Unicode.GetPreamble());
        System.IO.StringWriter sw = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new HtmlTextWriter(sw);
        Label lblheader = new Label();
        lblheader.Font.Size = 14;
        lblheader.Font.Bold = true;
        lblheader.Text = "Demo Detail";
        lblheader.RenderControl(hw);

        GrdExcel.RenderControl(hw);
        Response.Write(sw.ToString());
        Response.Flush();
        Response.End();
        GrdExcel.Visible = false;
    }
    catch (Exception ex)
    {
    }
}