DataGrid 导出Excel 出现的问题
在DataGrid 导出Excel 时,出现的下载界面,点击保存正常,但是点击打开时,系统又弹出这个窗口,要再次点击打开才能真正打开文件,请问大家知道为什么吗
代码:
DataGrid mydg;
mydg=(DataGrid)Page.FindControl("myDataGrid");
if(mydg==null)
{
mydg=(DataGrid)Page.FindControl("myGrid");
}
//如果DataGrid分页了,那么进行不分页的操作,然后进行导出,导出结束后再次重新绑定,
bool myFy=mydg.AllowPaging;
if(myFy==true)
{
mydg.AllowPaging=false;
mydg.AllowSorting=false;
Bindmydg(mydg);
}
string FileName="excel.xls";
System.Web.HttpResponse httpResponse = this.Response;
httpResponse.AppendHeader("Content-Disposition","attachment;filename="+HttpUtility.UrlEncode(FileName,System.Text.Encoding.UTF8)); //filename="*.xls";
httpResponse.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
httpResponse.ContentType ="application/ms-excel";
this.EnableViewState = false;
System.IO.StringWriter tw = new System.IO.StringWriter() ;
System.Web.UI.HtmlTextWriter hw = new System.Web.UI.HtmlTextWriter (tw);
mydg.RenderControl(hw);
string filePath = this.Server.MapPath("..")+"\\" +FileName;
System.IO.StreamWriter sw = System.IO.File.CreateText(filePath);
sw.Write(tw.ToString());
sw.Close();
//下载
Response.ContentType = "application/octet-stream";
Response.AppendHeader("Content-Disposition","attachment;filename=" + HttpUtility.UrlEncode(FileName,System.Text.Encoding.UTF8) + ";charset=GB2312");
System.IO.FileStream fs= System.IO.File.OpenRead(filePath);
long fLen=fs.Length;
int size=102400;//每100K同时下载数据
byte[] readData = new byte[size];//指定缓冲区的大小
if(size>fLen)size=Convert.ToInt32(fLen);
long fPos=0;
bool isEnd=false;
while (!isEnd)
{
if((fPos+size)>fLen)
{
size=Convert.ToInt32(fLen-fPos);
readData = new byte[size];
isEnd=true;
}
fs.Read(readData, 0, size);//读入一个压缩块
Response.BinaryWrite(readData);
fPos+=size;
}
fs.Close();
System.IO.File.Delete(filePath);
if(myFy==true&&mydg.AllowPaging==false)
{
mydg.AllowPaging=myFy;
Bindmydg(mydg);
}
httpResponse.End();