在教程中看到,以下可以将Datagrid的数据导出为excelResponse.ContentType="application/vnd.ms-excel";
Response.Charset="";
this.EnableViewState=false;
System.IO.StringWrite sw=new System.IO.StringWrite();
System.Web.UI.HtmlTextWrite hw=new System.Web.UI.HtmlTextWrite(sw);
dgShow.RenderControl(hw);//dgShow为该页一Datagrid
Response.Write(sw.ToString());
Response.End();问题是,如何指定导出的excel格式,比如我想导出excel 5.0的格式

解决方案 »

  1.   

    public static void ToExcel(System.Web.UI.Control ctl,string FileName)
    {
                HttpContext.Current.Response.Charset ="UTF-8";
                HttpContext.Current.Response.ContentEncoding =System.Text.Encoding.Default;
                HttpContext.Current.Response.ContentType ="application/ms-excel";
                HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+""+FileName+".xls");
                ctl.Page.EnableViewState =false;
                System.IO.StringWriter  tw = new System.IO.StringWriter();
                System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter(tw);
                ctl.RenderControl(hw);
                HttpContext.Current.Response.Write(tw.ToString());
                HttpContext.Current.Response.End();
    }    private void Button3_Click(object sender, System.EventArgs e)
    {
                ToExcel(this.DataGrid1,"filename");
    }
      

  2.   

    HttpContext.Current.Response.AppendHeader("Content-Disposition","attachment;filename="+""+FileName+".xls");
    ->
    HttpContext.Current.Response.AppendHeader("Content-Disposition","inline;filename="+""+FileName+".xls");
    这样可以尽量避免出现一个下载对话框,而是直接打开Excel文件。不过看你自己的需求了!