阅读文章(首页/程序开发/.NET教程/)

通用DataGrid导入Excel03或07

[日期:2008-07-04] 来源:  作者: [字体: ]

     不想多说了,经过反复实验,绝对不会有乱码问题,和导出数据量大情况下的没反映问题
  当然,是通过查看很多网上代码和园子里的高人代码,最后找到的解决办法
  而且在03和07中均可性的方案
  
   1if (dtData != null)
   2 {
   3 DataGrid dgExport = new DataGrid();
   4 dgExport.DataSource = dtData;
   5 dgExport.DataBind();
   6 dgExport.AllowPaging = false;
   7 System.Web.HttpResponse httpResponse = Page.Response;
   8 httpResponse.Clear();
   9 httpResponse.Buffer = true;
  10 httpResponse.Charset = "gb2312";
  11 string fileName = DateTime.Now.ToString("yyyyMMddHHmmssms") + ".xls";
  12 httpResponse.AppendHeader("Content-Disposition", "attachment;filename=" + HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8));
  13 httpResponse.ContentEncoding = System.Text.Encoding.GetEncoding("GB2312");
  14 httpResponse.ContentType = "application/ms-Excel";
  15 System.IO.StringWriter tw = new System.IO.StringWriter();
  16 System.Web.UI.HTMLTextWriter hw = new System.Web.UI.HTMLTextWriter(tw);
  17 dgExport.RenderControl(hw);
  18 string filePath = Server.MapPath("..") + fileName;
  19 System.IO.StreamWriter sw = System.IO.File.CreateText(filePath);
  20 sw.Write(tw.ToString());
  21 sw.Close();
  22 DownFile(httpResponse, fileName, filePath);
  23 httpResponse.End();
  24 }
  25
  下面是关键
   1private bool DownFile(System.Web.HttpResponse Response, string fileName, string fullPath)
   2 {
   3 System.IO.FileStream fs = System.IO.File.OpenRead(fullPath);
   4 try
   5 {
   6 Response.ContentType = "application/octet-stream";
   7 Response.AppendHeader("Content-Disposition", "attachment;filename=" +
   8 HttpUtility.UrlEncode(fileName, System.Text.Encoding.UTF8) + ";charset=GB2312");
   9 long fLen = fs.Length;
  10 int size = 102400;//每100K同时下载数据
  11 byte[] readData = new byte[size];//指定缓冲区的大小
  12 if (size > fLen) size = Convert.ToInt32(fLen);
  13 long fPos = 0;
  14 bool isEnd = false;
  15 while (!isEnd)
  16 {
  17 if ((fPos + size) > fLen)
  18 {
  19 size = Convert.ToInt32(fLen - fPos);
  20 readData = new byte[size];
  21 isEnd = true;
  22 }
  23 fs.Read(readData, 0, size);//读入一个压缩块
  24 if (readData.Length > 0)
  25 Response.BinaryWrite(readData);
  26 fPos += size;
  27 }
  28 return true;
  29 }
  30 catch
  31 {
  32 return false;
  33 }
  34 finally
  35 {
  36 fs.Close();
  37 System.IO.File.Delete(fullPath);
  38 }
  39 }
  only this
  
    


阅读:
录入:blue1000

评论 】 【 推荐 】 【 打印
上一篇:两种AOP实现方式的性能比较
下一篇:WCF学习(三)-------数据契约1
相关文章      
本文评论
发表评论


点评: 字数
姓名:

  • 尊重网上道德,遵守中华人民共和国的各项有关法律法规
  • 承担一切因您的行为而直接或间接导致的民事或刑事法律责任
  • 本站管理人员有权保留或删除其管辖留言中的任意内容
  • 本站有权在网站内转载或引用您的评论
  • 参与本评论即表明您已经阅读并接受上述条款