Gridview导出为Excel和怎样避免乱码

作者: Robin 分类: Asp.net 发布时间: 2008-07-03 12:54

Gridview导出为Excel
    尝试了一下Gridview导出为Excel,原本以为很简单,可是真正应用起来还是不太好弄的,呵呵,所想非所得。总结了一下应该注意下面几点:  
1.由于gridview的内容可能是分页显示的,因此,这里在每次导出excel时,先将gridview的allowpaging属性设置为false,然后databind()一下,确保搂到所有数据;  
2.不用单独设置导出的路径,导出时会弹出对话框让你确认保存位置;  
3.要写一个空的VerifyRenderingInServerForm方法(必须写),以确认在运行时为指定的ASP.NET  服务器控件呈现HtmlForm 控件;
4.导出后别忘记再重新设置其allowpaging属性;
    当我把这些都设置好以后,点击[导出],出现了 只能在执行 Render() 的过程中调用 RegisterForEventValidation(RegisterForEventValidation can only be  called during Render(); )

的错误,又检查代码,没发现问题啊,搞了一会弄不出来,然后搜索了一下,发现了解决办法:  
修改你的aspx文件中的:
<%@ Page  Language=”C#” EnableEventValidation = “false” AutoEventWireup=”true”  CodeFile=”SysUser.aspx.cs” Inherits=”Autho_SysUser2″ %>  
增加红色的部分就ok了。


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

    public static  void ToExcel(Control ctl, string FileName)
    {  
        HttpContext.Current.Response.Charset = “gb2312”;  
        HttpContext.Current.Response.ContentEncoding =  System.Text.Encoding.Default;  
        HttpContext.Current.Response.ContentType = “application/ms-excel”;  
        HttpContext.Current.Response.AppendHeader(“Content-Disposition”,  “attachment;filename=” + “” + FileName);
        ctl.Page.EnableViewState =  false;
        System.IO.StringWriter tw = new System.IO.StringWriter();  
        HtmlTextWriter hw = new HtmlTextWriter(tw);  
        ctl.RenderControl(hw);  
        HttpContext.Current.Response.Write(tw.ToString());  
        HttpContext.Current.Response.End();
    }

但是一试,便出现了乱码,解决方案如下  
    public static void Export(System.Web.UI.Page page, System.Web.UI.Control  dg, string fileName, string typeName)
    {  
        System.Web.HttpResponse httpResponse =page.Response;  
        httpResponse.AppendHeader  
                              (“Content-Disposition”, “attachment;filename=”  
                               + HttpUtility.UrlEncode(fileName,  System.Text.Encoding.UTF8));
        httpResponse.ContentEncoding =  System.Text.Encoding.GetEncoding(“GB2312”);
        httpResponse.ContentType  = typeName;
        System.IO.StringWriter tw = new  System.IO.StringWriter();
        System.Web.UI.HtmlTextWriter hw = new  System.Web.UI.HtmlTextWriter(tw);
        dg.RenderControl(hw);  
        string filePath = page.Server.MapPath(“..”) + fileName;  
        System.IO.StreamWriter sw = System.IO.File.CreateText(filePath);  
        sw.Write(tw.ToString());
        sw.Close();
          
        DownFile(httpResponse, fileName, filePath);  
        httpResponse.End();
    }
    public static bool  DownFile(System.Web.HttpResponse Response, string fileName, string fullPath)  
    {
        try
        {
            Response.ContentType =  “application/octet-stream”;  
            Response.AppendHeader(“Content-Disposition”,  “attachment;filename=” +
                HttpUtility.UrlEncode(fileName,  System.Text.Encoding.UTF8) + “;charset=GB2312”);  
            System.IO.FileStream fs = System.IO.File.OpenRead(fullPath);  
            long fLen = fs.Length;
            int size =  102400;//每100K同时下载数据
            byte[] readData = new byte[size];//指定缓冲区的大小  
            if (size > fLen) size = Convert.ToInt32(fLen);  
            long fPos = 0;
            bool isEnd = false;  
            while (!isEnd)
            {
                if ((fPos +  size) > fLen)
                {
                    size =  Convert.ToInt32(fLen – fPos);
                    readData = new byte[size];  
                    isEnd = true;
                }  
                fs.Read(readData, 0, size);//读入一个压缩块  
                Response.BinaryWrite(readData);
                fPos +=  size;
            }
            fs.Close();  
            System.IO.File.Delete(fullPath);
            return true;  
        }
        catch
        {
            return false;  
        }
    }
怎么调用?? 其实就是怎么调用Export这个函数罢了.  

以上方法可以很有效地解决导出的乱码问题

如果觉得我的文章对您有用,请随意打赏。您的支持将鼓励我继续创作!

发表评论

电子邮件地址不会被公开。 必填项已用*标注

标签云