• GridView导出到Excel或Word文件的C#代码


    前台代码:

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

    <!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 id="Head1" runat="server">
        <title>GridView导出到Excel或Word文件</title>
    </head>
    <body>
        <form id="form1" runat="server">
            <div>
                <asp:GridView ID="gvPersonList" runat="server" AutoGenerateColumns="False">
                    <Columns>
                        <asp:BoundField DataField="Id" HeaderText="编号" />
                        <asp:BoundField DataField="Name" HeaderText="姓名" />
                        <asp:TemplateField HeaderText="性别">
                            <ItemTemplate>
                                <%# Eval("Sex").ToString()=="true"?"男":"女" %>
                            </ItemTemplate>
                        </asp:TemplateField>
                        <asp:BoundField DataField="Age" HeaderText="年龄" />
                        <asp:TemplateField HeaderText="婚否">
                            <ItemTemplate>
                                <%# Boolean.Parse(Eval("Married").ToString())==true?"是":"否" %>
                            </ItemTemplate>
                        </asp:TemplateField>
                    </Columns>
                </asp:GridView>
                <asp:Button ID="btnToExcel" runat="server" OnClick="btnToExcel_Click" Text="导出到Excel" />
                <asp:Button ID="btnToWord" runat="server" OnClick="btnToWord_Click" Text="导出到Word" />
            </div>
        </form>
    </body>
    </html>

    后台代码:

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

    public partial class ExportDemo : System.Web.UI.Page
    {
        private string firstName = "赵钱孙李周吴郑王冯陈诸卫蒋沈韩杨朱秦尤许何吕施张孔曹严华";
        private string lastName = "猛勇刚强豹彪雁燕蓉菲";

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

        private void BindGridView()
        {
            DataTable myData = CreateDataTable();

            Session["MyData"] = myData;

            gvPersonList.DataSource = myData;

            gvPersonList.DataBind();

        }
        private DataTable CreateDataTable()
        {
            DataTable data = new DataTable();

            DataColumn dcld = new DataColumn("ID",typeof(Int32));

            //设置ID列自增
            dcld.AutoIncrement = true;

            //设置ID列初始值为1
            dcld.AutoIncrementSeed = 1;

            //设置ID列递增步长值为1
            dcld.AutoIncrementStep = 1;

            //将ID列添加到Table中
            data.Columns.Add(dcld);

            data.Columns.Add(new DataColumn("Name",typeof(string)));

            data.Columns.Add(new DataColumn("Age",typeof(Int32)));

            data.Columns.Add(new DataColumn("Sex",typeof(bool)));

            data.Columns.Add(new DataColumn("Married",typeof(bool)));

            DataRow dataRow = null;

            Random random = new Random();

            //随机生成20条记录
            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);

                //随机产生介于20至100之间的年龄
                int age = random.Next(20, 100);

                dataRow["Age"] = age;

                //随机设置性别
                bool sex = (random.Next(100) % 2 == 0) ? true : false;

                dataRow["Sex"] = sex;

                //男性结婚年龄大于22周岁,女性结婚年龄大于20周岁
                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>
        /// 导出为Excel文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnToExcel_Click(object sender, EventArgs e)
        {
            Response.Clear();

            Response.BufferOutput=true;

            //设定输出的字符集
            Response.Charset = "GB2312";

            //假定导出的文件名为FileName.xls
            Response.AppendHeader("Content-Disposition","attachment;filename=FileName.xls");

            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

            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();
        }
        /// <summary>
        /// 导出为Word文件
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        protected void btnToWord_Click(object sender, EventArgs e)
        {
            Response.Clear();

            Response.BufferOutput = true;

            //设定输出的字符集
            Response.Charset = "GB2312";

            //假定输出的文件名为FileName.Doc
            Response.AppendHeader("Content-Disposition","attachment;filename=FileName.doc");

            Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");

            //设置导出文件的格式
            Response.ContentType = "application/ms-word";

            //关闭ViewState
            gvPersonList.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();
        }

      //必须重写这个方法,方法体内不需任何操作,不然就会报错!

        public override void VerifyRenderingInServerForm(Control contorl)
        { }
    }

  • 相关阅读:
    python中常用的模块二
    python中常用的模块一
    python类与类的关系
    python类的成员
    关于python的面向对象
    python内置函数2
    python内置函数
    python fileinput模块
    python生成器
    python 迭代器
  • 原文地址:https://www.cnblogs.com/12go/p/2196161.html
Copyright © 2020-2023  润新知