导出数据,从Sql到Excel,但弹出对话框时,要点击两次按钮"打开",才可以打开文件.
另外:为什没有数据的地方无Excel格线?原本用的是ADO导出,但要在电脑上作一些设置,实用者嫌麻烦,
让我改程序,结果出现这样两个问题,如何解决?谢谢.
代码如下:
 protected void Export_Click(object sender, EventArgs e)
    {
        GridView gv = new GridView();
        Response.Clear();     
        Response.Buffer=   true;   
        Response.AppendHeader("Content-Disposition", "attachment;filename=temp_store.xls");  
        Response.ContentEncoding = System.Text.Encoding.GetEncoding("utf-8"); 
        Response.ContentType   =   "application/ms-excel"; //设置输出文件类型为excel文件。     
         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);
        Response.Charset = "GB2312"; 
        gv.DataSource=this.CreateExcelData((DataTable)ViewState["dt"]);
        gv.DataBind();
        gv.RenderControl(oHtmlTextWriter);     
        Response.Write(oStringWriter.ToString());   
        Response.End();
        Page.EnableViewState = true;
    }

解决方案 »

  1.   

    个人感觉最好是直接从dataset对象中导出会好点,如果从gridview导出,有分页的情况就只能导出当前页,有个现成的代码:
            private void ExportExcel(DataSet ds)
            {            System.IO.StringWriter sw = new System.IO.StringWriter();
                sw.WriteLine("用户名称,公司名称,登录IP,登录时间");
                foreach (DataRow dr in ds.Tables[0].Rows)
                {
                    sw.WriteLine(dr["UserName"] + "," + dr["OrgName"] + "," + dr["IP"] + "," + dr["LoginTime"]);
                }
                sw.Close();
                Response.AddHeader("Content-Disposition", "attachment; filename=filename.csv");
                Response.ContentType = "application/ms-excel";
                Response.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
                Response.Write(sw);
                Response.End();        }