Asp.net GridView 匯出到Excel

來源:互聯網
上載者:User

方法1、

(1.)Default.aspx

<%@ Page Language="C#" AutoEventWireup="true"  CodeFile="Default.aspx.cs" Inherits="_Default" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title>Untitled Page</title>
</head>
<body  runat="server">
    <form id="form1" runat="server">
    <div runat="server">
   
        <asp:GridView ID="GridView1" runat="server" AutoGenerateColumns="False"
            DataKeyNames="CustomerID" DataSourceID="SqlDataSource1" AllowPaging="True"
            BackColor="LightGoldenrodYellow" BorderColor="Tan" BorderWidth="1px"
            CellPadding="2" ForeColor="Black" GridLines="None">
            <FooterStyle BackColor="Tan" />
            <Columns>
                <asp:BoundField DataField="CustomerID" HeaderText="CustomerID" ReadOnly="True"
                    SortExpression="CustomerID" />
                <asp:BoundField DataField="CompanyName" HeaderText="CompanyName"
                    SortExpression="CompanyName" />
                <asp:BoundField DataField="ContactName" HeaderText="ContactName"
                    SortExpression="ContactName" />
                <asp:BoundField DataField="ContactTitle" HeaderText="ContactTitle"
                    SortExpression="ContactTitle" />
                <asp:BoundField DataField="Address" HeaderText="Address"
                    SortExpression="Address" />
                <asp:BoundField DataField="City" HeaderText="City" SortExpression="City" />
                <asp:BoundField DataField="Region" HeaderText="Region"
                    SortExpression="Region" />
                <asp:BoundField DataField="PostalCode" HeaderText="PostalCode"
                    SortExpression="PostalCode" />
                <asp:BoundField DataField="Country" HeaderText="Country"
                    SortExpression="Country" />
                <asp:BoundField DataField="Phone" HeaderText="Phone" SortExpression="Phone" />
                <asp:BoundField DataField="Fax" HeaderText="Fax" SortExpression="Fax" />
            </Columns>
            <PagerStyle BackColor="PaleGoldenrod" ForeColor="DarkSlateBlue"
                HorizontalAlign="Center" />
            <SelectedRowStyle BackColor="DarkSlateBlue" ForeColor="GhostWhite" />
            <HeaderStyle BackColor="Tan" Font-Bold="True" />
            <AlternatingRowStyle BackColor="PaleGoldenrod" />
        </asp:GridView>
        <asp:Button ID="Button1" runat="server" onclick="Button1_Click" Text="匯出" />
        <br />
   
    </div>
    <asp:SqlDataSource ID="SqlDataSource1" runat="server"
        ConnectionString="<%$ ConnectionStrings:ConnectionString %>"
        SelectCommand="Select * from Northwind.dbo.customers"></asp:SqlDataSource>
    </form>
</body>
</html>

其中:Web.Config中的資料庫設定為:

  <connectionStrings>
  <add name="ConnectionString" connectionString="Data Source=CCXP;User ID=sa;Password=19850613" providerName="System.Data.SqlClient"/>
 </connectionStrings>

大家可以根據自己的情況進行設定。

  (2.) Default.aspx.cs

using System;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;

public partial class _Default : System.Web.UI.Page
{
    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            DataBind();//綁定資料
        }
    }
    protected void Button1_Click(object sender, EventArgs e)
    {
        Response.Clear();
        System.Web.HttpContext curContext = System.Web.HttpContext.Current;

        Response.AddHeader("content-disposition", "attachment;filename=FileName.xls");
        Response.Charset = "UTF-8";//設定字元集
        curContext.Response.ContentEncoding = System.Text.Encoding.UTF8;//設定編碼集
      
        Response.ContentType = "application/vnd.xls";
        System.IO.StringWriter stringWrite = new System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);
        GridView1.AllowPaging = false;//寫到Excel的資料不用分頁
        BindData();
        GridView1.RenderControl(htmlWrite);
        Response.Write(stringWrite.ToString());//向用戶端寫資料
        Response.End();
        GridView1.AllowPaging = true;//恢複分頁
        BindData();

    }
    private void BindData()
    {
        GridView1.DataBind();
    }
    public override void VerifyRenderingInServerForm(Control control)//這個方法不寫的話可能報錯類型“GridView”的控制項“GridView1”必須放在具有 runat=server 的表單標記內。
    {
        // Confirms that an HtmlForm control is rendered for
    }

}
方法2:不用重寫VerifyRenderingInServerForm方法,Button1_Click不一樣,其它的一樣。

 protected void Button1_Click(object sender, EventArgs e)
    {

StringBuilder sb = new StringBuilder();
StringWriter sw = new StringWriter(sb);
HtmlTextWriter htw = new HtmlTextWriter(sw);

Page page = new Page();
HtmlForm form = new HtmlForm();

GridView1.EnableViewState = false;

page.EnableEventValidation = false; 

// Realiza las inicializaciones de la instancia de la clase Page que requieran los diseñadores RAD.
page.DesignerInitialize(); 

page.Controls.Add(form);

  GridView1.AllowPaging = false;//寫到Excel的資料不用分頁
   BindData();
form.Controls.Add(GridView1);

page.RenderControl(htw);

Response.Clear();
Response.Buffer = true;
Response.ContentType = "application/vnd.ms-excel";
Response.AddHeader("Content-Disposition", "attachment;filename=data.xls");
Response.Charset = "UTF-8";
Response.ContentEncoding = Encoding.Default;
Response.Write(sb.ToString());
Response.End();

    GridView1.AllowPaging = true;//恢複分頁
     BindData();

}
希望對碰到這類需求的朋友有協助。

 

聯繫我們

該頁面正文內容均來源於網絡整理,並不代表阿里雲官方的觀點,該頁面所提到的產品和服務也與阿里云無關,如果該頁面內容對您造成了困擾,歡迎寫郵件給我們,收到郵件我們將在5個工作日內處理。

如果您發現本社區中有涉嫌抄襲的內容,歡迎發送郵件至: info-contact@alibabacloud.com 進行舉報並提供相關證據,工作人員會在 5 個工作天內聯絡您,一經查實,本站將立刻刪除涉嫌侵權內容。

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.