惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

博客园_首页
Vercel News
Vercel News
月光博客
月光博客
S
SegmentFault 最新的问题
A
About on SuperTechFans
Microsoft Security Blog
Microsoft Security Blog
U
Unit 42
Google DeepMind News
Google DeepMind News
Engineering at Meta
Engineering at Meta
B
Blog RSS Feed
Y
Y Combinator Blog
云风的 BLOG
云风的 BLOG
N
Netflix TechBlog - Medium
小众软件
小众软件
WordPress大学
WordPress大学
G
Google Developers Blog
Recent Announcements
Recent Announcements
H
Hackread – Cybersecurity News, Data Breaches, AI and More
P
Proofpoint News Feed
Blog — PlanetScale
Blog — PlanetScale
MongoDB | Blog
MongoDB | Blog
F
Fortinet All Blogs
博客园 - 【当耐特】
I
InfoQ

博客园 - 特困生

腾讯围脖邀请 office2010 bata 4536 激活问题 windows7 64位 建行捷德UKey无法使用的问题 清除windows7 在任务栏上显示的图标和通知,自定义选项内的图标 Windows7 IIS 7.0 局域网无法访问的解决 - 特困生 c#.net 邮件发送 Maxdos v6 pxe 网刻教程 去掉微软的正版验证 高流量Web2.0网站性能调优的14条准则 Team Foundation但服务器部署 解决visual studio自动调试问题 Visual Studio 2005的各个版本 生成汉字验证码 - 特困生 - 博客园 C#常用函数和方法集汇总 sql2000和sql2005共存问题 安装vs2005sp1补丁注意事项 XMLHttpRequest对象 Web页面折线图控件(可以直接绑定数据) c#绘制曲线图
GridView数据导出到Excel中
特困生 · 2007-04-19 · via 博客园 - 特困生

将GridView中数据导出到Excel中

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

    }

    
    
private void BindData()
    
{
        
string query = "SELECT * FROM orders";
        SqlConnection conn 
= new SqlConnection("server=.;database=northwind;uid=sa;pwd=sa");
        SqlDataAdapter ad 
= new SqlDataAdapter(query, conn);
        DataSet ds 
= new DataSet();
        ad.Fill(ds);
        GridView1.DataSource 
= ds.Tables[0];
        GridView1.DataBind();

    }



    
public override void VerifyRenderingInServerForm(Control control)
    
{

        
    }


    
protected void Button2_Click(object sender, EventArgs e)
    
{
        Response.Clear();

        Response.AddHeader(
"content-disposition","attachment;filename=FileName.xls");

        Response.Charset 
= "gb2312";
        Response.ContentType 
= "application/vnd.xls";

        System.IO.StringWriter stringWrite 
= new System.IO.StringWriter();

        System.Web.UI.HtmlTextWriter htmlWrite 
= new HtmlTextWriter(stringWrite);


        GridView1.AllowPaging 
= false;
        BindData();
        GridView1.RenderControl(htmlWrite);

        Response.Write(stringWrite.ToString());

        Response.End();

        GridView1.AllowPaging 
= true;
        BindData();

    }

导出成功!
注意如果数据源是NorthWind中的Products表(原因不清楚,应该还有其他的数据源也会出现这种情况)
会出现异常
只能在执行 Render() 的过程中调用 RegisterForEventValidation;有两种方法可以解决这个问题:
1.修改web.config(不推荐)<pages enableEventValidation ="false" ></pages>
2.直接在导出Execl的页面修改

<%@ Page Language="C#" EnableEventValidation = "false" AutoEventWireup="true"

 CodeFile
="ExportGridView.aspx.cs" Inherits="ExportGridView" 
%>