• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    公众号

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

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

前台代码:

<%@ 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 />
        </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)
    { }
}


鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
热门推荐
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap