导出Exexcl类

本文介绍如何使用ASP.NET将GridView控件的数据导出为Excel文件,通过设置Response对象和利用HtmlTextWriter来实现数据的格式化输出。

前台:

<%@ Page Language="C#" AutoEventWireup="true" EnableEventValidation="false"  CodeBehind="index1.aspx.cs" Inherits="benz_CSI.toExecl.index1" %>

<!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>无标题页</title>
</head>
<body>
    <form id="form1" runat="server">
    <div style="font-weight: 700">
 
        <asp:Button ID="btnToExL" runat="server" Text="导出EXECL" onclick="btnToExL_Click" />
        <asp:GridView ID="GridView1" runat="server">
        </asp:GridView>
   
    </div>
    </form>
</body>
</html>

 

后台:

using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Xml.Linq;
namespace benz_CSI.toExecl
{
    public partial class index1 : System.Web.UI.Page
    {
        public override void VerifyRenderingInServerForm(Control control)
        {
            //base.VerifyRenderingInServerForm(control);
        }

        JiaFaAndXD jiafa = new JiaFaAndXD();
        protected void Page_Load(object sender, EventArgs e)
        {
            if (!IsPostBack)
            {
                GridView1.DataSource = jiafa.GetList2("");
                GridView1.DataBind();
            }
        }

        private void ToExcel(GridView gv, string name)
        {
            Response.Clear();
            Response.AddHeader("content-disposition", "attachment;filename=" + HttpUtility.UrlEncode(name + ".xls", System.Text.Encoding.UTF8));
            Response.Charset = "gb2312";
            Response.ContentType = "application/vnd.xls";
            System.IO.StringWriter stringWrite = new System.IO.StringWriter();
            System.Web.UI.HtmlTextWriter htmlWrite = new HtmlTextWriter(stringWrite);

            gv.AllowPaging = false;//将分页等属性取消
            gv.AllowSorting = true;//将允许排序属性取消
            gv.PagerStyle.ForeColor = System.Drawing.Color.White;
            gv.FooterStyle.ForeColor = System.Drawing.Color.White;
            gv.RenderControl(htmlWrite);

            Response.Write(stringWrite.ToString());
            Response.End();
        }

        protected void btnToExL_Click(object sender, EventArgs e)
        {
            ToExcel(GridView1, "能量值");
        }
    }
}

转载于:https://www.cnblogs.com/wwy224y/p/execl.html

评论
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符  | 博主筛选后可见
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值