DataGrid 导出Excel 出现的问题

yicky_2005 2006-08-08 12:38:15
在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();
...全文
208 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
linfuguo 2006-08-19
  • 打赏
  • 举报
回复
http://www.cnblogs.com/linfuguo/archive/2006/08/19/480976.html
linfuguo 2006-08-18
  • 打赏
  • 举报
回复
AIRFLYNET(汪洋中的一条船)
出现的错误,正是不建议这样做的原因!
还是老实的把DataSet直接导入吧!
AIRFLYNET 2006-08-15
  • 打赏
  • 举报
回复
DataGrid 导入到Excel 时出错
Control 'grdRohstest__ctl2_APPID' of type 'TextBox' must be placed inside a form tag with runat=server.

ctl.RenderControl(hw);
linfuguo 2006-08-11
  • 打赏
  • 举报
回复
建议不要这样直接导出
把dataset导出不是更好吗?
参见:
http://linfuguo.cnblogs.com
中的asp.net导出excel的文档
yicky_2005 2006-08-10
  • 打赏
  • 举报
回复
自己顶。。。。。

62,254

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术交流专区
javascript云原生 企业社区
社区管理员
  • ASP.NET
  • .Net开发者社区
  • R小R
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

.NET 社区是一个围绕开源 .NET 的开放、热情、创新、包容的技术社区。社区致力于为广大 .NET 爱好者提供一个良好的知识共享、协同互助的 .NET 技术交流环境。我们尊重不同意见,支持健康理性的辩论和互动,反对歧视和攻击。

希望和大家一起共同营造一个活跃、友好的社区氛围。

试试用AI创作助手写篇文章吧