• Asp.net中导出Excel文档(Gridview)


    主要思路,通过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)
            {
            }
  • 相关阅读:
    开启 clr enabled
    索引查看
    nginx 安装
    mysql中int(10)与int(11)有什么区别吗?
    1.安卓开发基础1~6笔记
    Vue项目搭建基础之Vue-cli模版测试
    alert执行顺序
    介绍call和apply
    a链接易混淆与form表单简易验证用法详解
    js正则知识点
  • 原文地址:https://www.cnblogs.com/likeli/p/3877458.html
Copyright © 2020-2023  润新知