日期:2014-05-19  浏览次数:20541 次

datagrid导出为excel时为何有时成功,有时不成功
datagrid导出为excel时为何有时成功,有时不成功
我用的是2003
成功时弹出系统另存为对话框的文件类型为Mircrosoft   Excel
不成功时弹出系统另存为对话框的文件类型为Html   Document
不同的datagrid调用同一个函数,1个datagrid有时成功,有时不成功
另外2个几乎都不成功

        Public   Shared   Sub   Convert(ByVal   ADatagrid   As   DataGrid,   ByVal   response   As   System.Web.HttpResponse)
                response.Clear()
                response.AppendHeader( "Content-Disposition ",   "attachment;filename=Excel.xls ")
                'response.AddHeader( "content-disposition ",   "inline;filename=Excel.xls ")
                response.Charset   =   " "
                'set   the   response   mime   type   for   excel
                response.ContentType   =   "application/vnd.ms-excel "
                'response.ContentType   =   "application/ms-excel "
                '               response.contenttype   =   "application/vnd.ms-excel ";
                'response.addheader( "content-disposition ",   "inline;filename= "
                '     +       httputility.urlencode( "下载文件.xls ",encoding.utf8       )       );      


                'create   a   string   writer
                Dim   stringWrite   As   New   System.IO.StringWriter
                'create   an   htmltextwriter   which   uses   the   stringwriter
                Dim   htmlWrite   As   New   System.Web.UI.HtmlTextWriter(stringWrite)
                ADatagrid.RenderControl(htmlWrite)

                response.Write(stringWrite.ToString)
                response.End()
        End   Sub


------解决方案--------------------
点击Button2时保存
private void Button2_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.UTF7;

//设置输出文件类型为excel文件。
Response.ContentType = "application/ms-excel ";
System.IO.StringWriter oStringWriter = new System.IO.StringWriter();
System.Web.UI.HtmlTextWriter oHtmlTextWriter = new System.Web.UI.HtmlTextWriter(oStringWriter);
this.DataGrid1.RenderControl(oHtmlTextWriter);
Response.Output.Write(oStringWriter.ToString());
Response.Flush();