程序師世界是廣大編程愛好者互助、分享、學習的平台,程序師世界有你更精彩!
首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫知識
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
 程式師世界 >> 編程語言 >> .NET網頁編程 >> ASP.NET >> 關於ASP.NET >> Asp.net中如何導出Excel文檔(Gridview)

Asp.net中如何導出Excel文檔(Gridview)

編輯:關於ASP.NET

主要思路,通過GridView來導出文檔。新建一個Aspx頁面,頁面創建GridView控件,後台綁定好數據源。
然後load中直接打印即可導出

前台的GridView

<asp:GridView ID="GridView1" BorderColor="Black" runat="server" AutoGenerateColumns="False"
            Font-Size="12px" Width="656px" AllowSorting="True" Height="172px">
            <Columns>
                <asp:BoundField DataField="Name" HeaderText="姓名" />
                <asp:BoundField DataField="Sex" HeaderText="性別" />
                <asp:BoundField DataField="BirthDay" HeaderText="出生日期" />
                <asp:BoundField DataField="StudentId" HeaderText="身份證號" />
                <asp:BoundField DataField="JieduId" HeaderText="借讀證號" />
                <asp:BoundField DataField="Familymemberinfo_Name1" HeaderText="第一監護人姓名" />
            </Columns>
            <HeaderStyle BackColor="Azure" Font-Size="12px" HorizontalAlign="Center" />
            <RowStyle HorizontalAlign="Center" />
            <PagerStyle HorizontalAlign="Center" />
        </asp:GridView>

後台:

/// <summary>
        /// 定義導出Excel的函數
        /// </summary>
        /// <param name="FileType"></param>
        /// <param name="FileName"></param>
        private void Export(string FileType, string FileName)
        {
            for (int i = 0; i < GridView1.Rows.Count; i++)
            {
                //這裡給指定的列編輯格式,將數字輸出為文本,防止數字溢出
                GridView1.Rows[i].Cells[3].Attributes.Add("style", "vnd.ms-excel.numberformat:@");
            }
            Response.Charset = "GB2312";
            //Response.ContentEncoding = System.Text.Encoding.UTF8;
            Response.ContentEncoding = System.Text.Encoding.GetEncoding("gb2312");
            Response.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
            Response.ContentType = FileType;
            this.EnableViewState = false;
            StringWriter tw = new StringWriter();
            HtmlTextWriter hw = new HtmlTextWriter(tw);
            GridView1.RenderControl(hw);
            Response.Write(tw.ToString());
            Response.End();
        }
    
        /// <summary>
        /// 此方法必重寫,否則會出錯
        /// </summary>
        /// <param name="control"></param>
        public override void VerifyRenderingInServerForm(Control control)
        {
        }

作者:憤怒的TryCatch

出處:http://www.cnblogs.com/likeli/

  1. 上一頁:
  2. 下一頁:
Copyright © 程式師世界 All Rights Reserved