代码:
HttpContext.Current.Response.Charset ="";
HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename=new.xls");
HttpContext.Current.Response.AppendHeader("Content-Disposition","inline;filename=new.xls");
HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.GetEncoding("utf-8"); 
HttpContext.Current.Response.ContentType ="application/ms-excel";//image/JPEG;text/HTML;image/GIF;vnd.ms-excel/msword
dg.Page.EnableViewState =false;
System.IO.StringWriter  tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
dg.RenderControl(hw);
HttpContext.Current.Response.Write(tw.ToString());
HttpContext.Current.Response.End();
问题:
    <1>当第一次点击导入的时候,提示打开或者保存。当点击打开的时候出现的不是excel文件,而是原来的datagird页面,只是文件名变成了htm。只有第二次打开才能正常显示为excel文件。保存也是这个问题!
    <2>当把代码中的attachment改成inline以后实现了没有提示的导入excel。但是问题在于原来的页面退回不了!
    请大家给予指点!适当的给些代码!万分感激!!!!

解决方案 »

  1.   

    private void btnexcel_Click(object sender, System.EventArgs e)
    {
    Response.Clear(); 
    Response.Buffer= true; 
    Response.Charset="GB2312";
    Response.AppendHeader("Content-Disposition","attachment;filename=FileName.xls");  Response.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
    //设置输出流为简体中文
    Response.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。
    application/ms-word || application/ms-txt || application/ms-html || 或其他浏览器可直接支持文档 
     
    this.EnableViewState = false;    
    System.Globalization.CultureInfo myCItrad = new System.Globalization.CultureInfo("ZH-CN",true);
    System.IO.StringWriter oStringWriter = new System.IO.StringWriter(myCItrad); 
    System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
    this.datagridname.RenderControl(oHtmlTextWriter); 
    //datagridname是datagrid名
    Response.Write(oStringWriter.ToString());
    Response.End();
    }我都是这样做的,没问题的,试试
      

  2.   

    http://dotnet.aspx.cc/ShowDetail.aspx?id=8A4CBF47-B888-4832-3389-ED3A3A3C8AAB
      

  3.   

    谢谢xulovewei(耗子爱猫咪) 问题还是一样,第一次打开或保存是原来的datagrid页面!
    当DataGrid分页的时候怎么提示错误!请大家指点!!!!
      

  4.   

    有可能是你缓存或者连接指向的问题,上面的代码不会错的,楼主再好好查查:)
    分页错误有可能是你的CurrentPageIndex的问题