首页 新闻 会员 周边

asp.net关于用Response输出Excel的问题

0
悬赏园豆:10 [已解决问题] 解决于 2016-12-07 11:02

        public static void GridViewToExcel(GridView ctrl, string FileType, string         FileName)
        {
            HttpContext.Current.Response.Clear();
            HttpContext.Current.Response.Charset = "GB2312";
            HttpContext.Current.Response.ContentEncoding = Encoding.UTF8;//注意编码
            HttpContext.Current.Response.AppendHeader("Content-Disposition",
                "attachment;filename=" + HttpUtility.UrlEncode(FileName, Encoding.UTF8).ToString());
            HttpContext.Current.Response.ContentType = FileType;//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword 
            ctrl.AllowPaging = false;
            ctrl.DataBind();

            StringBuilder sbOutput = new StringBuilder("");
            for (int row = 0; row < ctrl.Rows.Count; row++)
            {
                for (int column = 1; column < ctrl.Rows[row].Cells.Count; column++)//从1开始是为了不加入选择的linkbutton
                {
                    sbOutput.Append(ctrl.Rows[row].Cells[column].Text.ToString() + "\t");
                }
                sbOutput.Append("\n");
            }

            HttpContext.Current.Response.Write(sbOutput.ToString());
            HttpContext.Current.Response.End();
        }

        protected void btn_GenerateExcel_Click(object sender, EventArgs e)
        {
            GridViewToExcel(gv_userScore, "application/ms-excel","分管用户成绩.xls");
        }

 

 

小弟的代码如上,我这是用StringBuilder拼了一个字符串然后用Response往客户端写的数据,但是下载好Excel并打开以后,发现整个页面的数据都被下载了,包括button包括其他的元素,小弟表示十分费解,哪位能帮忙看一下我错在哪里?

PS:VerifyRenderingInServerForm这个方法我重写了,EnableEventValidation ="false"这个我也在前台中加了

微澜的主页 微澜 | 初学一级 | 园豆:-1
提问于:2014-05-12 21:30
< >
分享
最佳答案
0

(1)如果一定要用这种非原生的excel,你可以post到一个新的页面,比如GenerateExcel.aspx。在这个页面中,加入你封装在公用模块中的一段代码,不要写在页面中。

(2)可以用NPOI生成原生的Excel

收获园豆:10
邀月 | 高人七级 |园豆:25475 | 2014-05-13 07:36

NPOI这种方式我不太了解,这种方法是在客户端生成Excel还是在服务器端生成Excel?

微澜 | 园豆:-1 (初学一级) | 2014-05-13 19:41

@微澜: NPOI是独立的组件,不需要客户端安装Excel,只要使用正常的浏览器即可。

http://tonyqus.sinaapp.com/archives/tag/npoi

http://zzk.cnblogs.com/s?t=b&w=NPOI%20%E5%AF%BC%E5%87%BAexcel

最重要的是可以使用模板格式化报表

http://www.cnblogs.com/downmoon/archive/2011/04/16/2017603.html

邀月 | 园豆:25475 (高人七级) | 2014-05-14 11:22
其他回答(2)
0

依稀记得公司曾经使用过这个方法,是不会导出其他元素的,

lucika.zh | 园豆:62 (初学一级) | 2014-05-13 11:48
0

Response.Clear();
Response.Buffer = true;
Response.AppendHeader("Content-Disposition", "attachment;filename=" + DateTime.Now.ToString("yyyyMMdd") + ".xls");
Response.ContentEncoding = System.Text.Encoding.Default;
Response.ContentType = "application/vnd.ms-excel";  

Response.Write(”内容“);

 Response.End();

sunlary | 园豆:934 (小虾三级) | 2014-05-13 14:58
清除回答草稿
   您需要登录以后才能回答,未注册用户请先注册