GridView를 Excel 또는 Word 파일로 내보내기

10667 단어 UIWebExcelasp.netasp
프런트 페이지:
 
   
<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation="false" CodeFile="Default4.aspx.cs" Inherits="Default4" %>

<!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>    </title>
</head>
<body>
    <form id="form1" runat="server">
    <div>
        <asp:GridView ID="gvPersonList" runat="server" AutoGenerateColumns="False" 
            AllowPaging="True" onpageindexchanging="gvPersonList_PageIndexChanging">
    <Columns>
    <asp:TemplateField HeaderText="  ">
    <ItemTemplate>
    <asp:Label ID="Label1" runat="server" Text='<%# Bind("Id") %>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>
    <asp:BoundField DataField="Name" HeaderText="  " />
    <asp:TemplateField HeaderText="  ">
    <ItemTemplate>
    <asp:Label ID="Label2" runat="server" 
    Text='<%# Eval("Sex").ToString().ToLower()=="true"?" ":" " %>'></asp:Label>
    </ItemTemplate>
    </asp:TemplateField>
     <asp:TemplateField HeaderText="  ">
     <ItemTemplate>
     <asp:Label ID="Label3" runat="server" 
     Text='<%#Boolean.Parse(Eval("Married").ToString())==true?" ":" " %>'></asp:Label>
     </ItemTemplate>
     </asp:TemplateField>
     </Columns>
     </asp:GridView>
     <asp:Button ID="btnToExcel" runat="server" Text="  Excel" 
      onclick="btnToExcel_Click" />
     <asp:Button ID="btnToWord" runat="server" Text="  Word" 
      onclick="btnToWord_Click" />
    </div>
    </form>
</body>
</html>

 
 
using System;
using System.Collections;
using System.Configuration;
using System.Data;
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;

public partial class Default4 : System.Web.UI.Page
{

    private string firstName = "                            ";
    private String lastName = "          ";

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            BindGridView();
        }
    }

    //    GridView  
    private void BindGridView()
    {
        gvPersonList.DataSource = CreateDataTable();
        gvPersonList.DataBind();
    }

    //    DataTable
    private DataTable CreateDataTable()
    {
        DataTable data = new DataTable();
        //ID 
        DataColumn dcid = new DataColumn("id", typeof(Int32));
        //  ID     
        dcid.AutoIncrement = true;
        //  ID     1
        dcid.AutoIncrementSeed = 1;
        //  ID      1
        dcid.AutoIncrementStep = 1;
        // ID    DataTable 
        data.Columns.Add(dcid);
        data.Columns.Add(new DataColumn("Name", typeof(String)));
        data.Columns.Add(new DataColumn("Age", typeof(int)));
        data.Columns.Add(new DataColumn("Sex", typeof(bool)));
        data.Columns.Add(new DataColumn("Married", typeof(bool)));
        DataRow dataRow = null;
        Random random = new Random();
        for (int i = 0; i < 20; i++)
        {
            dataRow = data.NewRow();
            //      
            dataRow["Name"] = firstName.Substring(random.Next(firstName.Length), 1)
            + lastName.Substring(random.Next(lastName.Length), 1);
            //      
            int age = random.Next(20, 100);
            dataRow["Age"] = age;
            //      
            bool sex = (random.Next(100) % 2 == 0) ? true : false;
            dataRow["Sex"] = sex;
            if (sex == true && age >= 22 || sex == false && age >= 20)
            {
                dataRow["Married"] = (random.Next(500) % 2 == 0) ? true : false;
            }
            else
            {
                dataRow["Married"] = false;
            }

            data.Rows.Add(dataRow);
        }

        return data;
    }

    /// <summary>
    ///       
    /// </summary>
    /// <param name="FileType">    MIME  </param>
    /// <param name="FileName">       </param>
    private void Exprot(String FileType, String FileName)
    {
        Response.Clear();
        Response.BufferOutput = true;
        //       
        Response.Charset = "GB2312";
        Response.ContentEncoding = System.Text.Encoding.UTF8;
        Response.AppendHeader("Content-Disposition", "attachment;filename="
        + HttpUtility.UrlEncode(FileName, System.Text.Encoding.UTF8));
        //     HttpMiME  (      )
        Response.ContentType = FileType;
        //  ViewState
        Page.EnableViewState = false;
        System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("ZH-CN", true);
        System.IO.StringWriter stringWriter = new System.IO.StringWriter(cultureInfo);
        HtmlTextWriter textWriter = new HtmlTextWriter(stringWriter);
        gvPersonList.RenderControl(textWriter);
        // HTML     
        Response.Write(stringWriter.ToString());
        Response.End();
        Response.Flush();
    }

    //  Excel
    protected void btnToExcel_Click(object sender, EventArgs e)
    {
        //Response.Clear();
        //Response.BufferOutput = true;
        ////        
        //Response.Charset = "utf-8";
        ////         FileName.xls
        //Response.AppendHeader("Content-Disposition", "attachment;filename=FileName.xls");
        //Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8");
        ////         
        //Response.ContentType = "application/ms-excel";
        ////  ViewState
        //EnableViewState = false;
        //System.Globalization.CultureInfo cultureInfo = new System.Globalization.CultureInfo("ZH-CN", true);
        //System.IO.StringWriter stringWriter = new System.IO.StringWriter(cultureInfo);
        //System.Web.UI.HtmlTextWriter textWriter = new System.Web.UI.HtmlTextWriter(stringWriter);
        //gvPersonList.RenderControl(textWriter);
        //// HTML     
        //Response.Write(stringWriter.ToString());
        //Response.End();
        Exprot("application/ms-excel","Employee.xls");
    }

    //  Word
    protected void btnToWord_Click(object sender, EventArgs e)
    {
        //               
        Exprot("application/ms-word", "Employee.doc");
    }

    //           ASP.NET          HtmlForm    。
    //(  Asp.Net          HTMLForm   )
    public override void VerifyRenderingInServerForm(Control control)
    {
    /*      , asp.net 1.1             ,
    *     override void VerifyRenderingInServerForm(Control control)    
    *   asp.net2.0 ,        ,RenderControl          render  
    *           ,                     。          ,
    *           Form ,         ,
    *     asp.net2.0         RenderControl    Render         。
    *    override VerifyRenderingInServerForm    。
    *   override void VerifyRenderingInServerForm(Control control)    ,
    *           */
       //base.VerifyRenderingInServerForm(control);
    }

    /// <summary>
    ///   
    /// </summary>
    protected void gvPersonList_PageIndexChanging(object sender, GridViewPageEventArgs e)
    {
        gvPersonList.PageIndex = e.NewPageIndex;
        BindGridView();
    }
}

 
주의해야 할 것은:asp.net2.0 환경에서 Verify Rendering InserverForm (Control control) 이 방법이 오버라이드를 하지 않으면 '오류 알림: 형식' GridView '컨트롤' GridView1 '은runat=server가 있는 창 표시줄에 넣어야 합니다.' 오류가 발생합니다.
페이지를 나누는 경우 한 페이지의 데이터를 받지 않으려면 모든 데이터를 내보내야 합니다.
1.gridview의 내용은 페이지로 나눌 수 있기 때문에 excel을 내보낼 때마다 gridview의allowpaging 속성을false로 설정하고 데이터bind()로 설정하여 모든 데이터를 확보합니다.
2. 내보낼 경로를 따로 설정하지 않고 내보낼 때 저장 위치를 확인하는 대화 상자가 나타납니다.
3. 런타임에 지정된 ASP가 있는지 확인하기 위해 빈 Verify Rendering InServerForm 메서드를 쓰십시오.NET 서버 컨트롤HtmlForm 컨트롤 렌더링
4. 내보내고 allowpaging 속성을 다시 설정하는 것을 잊지 마세요.내가 이것들을 모두 설정한 후에 [내보내기]를 누르면 Render ()를 실행하는 과정에서만 Register For Event Validation (Register For Event Validation can only be called during Render () 를 호출할 수 있습니다.의 오류, 코드를 다시 검사했는데 문제가 발견되지 않았습니다. 잠시 후에 검색해 보니 해결 방법이 발견되었습니다.: aspx 파일의 수정: <%@ Page Language = "C#"Enable Event Validation = "false"AutoEvent Wireup = "true"CodeFile = "SysUser.aspx.cs"Inherits = "Autho SysUser2"%>
빨간 부분을 추가하면 OK.
 
 protected void btnToWord_Click(object sender, EventArgs e)
    {
        gvPersonList.AllowPaging = false;
        gvPersonList.AllowSorting = false;
        BindGridView();
        Exprot("application/ms-word", "Employee.doc");
        gvPersonList.AllowPaging = true;
        gvPersonList.AllowSorting = true;
        BindGridView();
    }

 

좋은 웹페이지 즐겨찾기