sunfei

万事烦扰,皆由心生,心不动,何来纷扰!
  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

将GridView导出到Excel并防止内容乱码

Posted on 2008-11-17 10:36  sunfei  阅读(261)  评论(0编辑  收藏  举报
我在数据库中建一个proc_ViewDriverDicpatch的储存过程,该储存过程主要完成对数据表进行交叉数据,完成交叉表功能,调用过程如下:

 

    public void BindData()
    
{
        Yesidea.DAO.DbHelperSQL dbhelper 
= new Yesidea.DAO.DbHelperSQL(new Yesidea.DAO.BaseDAO());
        SqlParameter[] parameters 
= {
                    
new SqlParameter("@TableName", SqlDbType.VarChar,50),
                    
new SqlParameter("@纵轴", SqlDbType.VarChar,50),
                    
new SqlParameter("@横轴", SqlDbType.VarChar,50),
                    
new SqlParameter("@表体内容", SqlDbType.VarChar,20),
                    
new SqlParameter("@是否加横向合计", SqlDbType.Bit),
                    
new SqlParameter("@是否加纵向合计", SqlDbType.Bit)}
;
        parameters[
0].Value = "ViewDicpatchDriver";
        parameters[
1].Value = "dname";
        parameters[
2].Value = "udept";
        parameters[
3].Value = "mileage";
        parameters[
4].Value = 1;
        parameters[
5].Value = 1;
        DataSet ds 
= dbhelper.RunProcedure("proc_ViewDriverDicpatch", parameters, "ViewDicpatchDriver");
        
this.GridView1.DataSource = ds;
        
this.GridView1.DataBind();
        
this.GridView1.HeaderRow.Cells[0].Text = "司机姓名\部门";
    }

输出为 Excel并防止文件内容乱码的代码如下:

    protected void btnExport_Click(object sender, EventArgs e)
    
{
        Response.Clear();
        Response.AddHeader(
"content-disposition""attachment;filename="" + Server.UrlEncode("FileName.xls"+ "");
        Response.Charset 
= "GB2312";
        Response.ContentEncoding 
= System.Text.Encoding.GetEncoding("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();
    }

注意:在页面中千万别忘了添加如下代码。

 

    public override void VerifyRenderingInServerForm(Control control)
    
{
        
// Confirms that an HtmlForm control is rendered for
    }