重重的壳裹着轻轻的仰望

I smile when I'm angry. I cheat and I lie. I do what I have to do ··· To get by.

导航

一种值得推荐的导出到EXCEL文件方式

Posted on 2007-10-31 17:50  暴走的猪  阅读(933)  评论(3编辑  收藏  举报
这种方式的原理是,在某页面(任何页面比如a.htm),把要导出的内容或结果集,通过表单提交到一个b.aspx页面。
aspx页面中,生成一个具有唯一文件名的excel文件,然后自动输出到前台。由前台来保存。
1.
a.htm页面,只需要把表单提交到b.aspx中即可。至于要提交什么内容,放入表单中的hidden控件即可。
你甚至可以动态改变hidden控件的value的值(这个很有用)。
关键字:
<form method="post" action="b.aspx" target="_blank">
<input type="hidden" name="TextSql" value="要提交的内容" ID="TextSql"></input>
</form>


2.
在aspx页面后台关键代码:


using System.IO;
using System.Text;

 // 接收表单的值
  private void Page_Load(object sender, System.EventArgs e)
  {
  
   string destString = Request.Form["TextSql"].ToString();
   ExportToFile(destString);

  }
 

//存为excel文件
 private void ExportToFile(string esql)
  {
   //new 一个 guid
   string FileName = Guid.NewGuid().ToString() + ".xls"; //GUID生成唯一文件名
   string FileType="application/ms-excel";
   try
   {
    System.Web.HttpResponse httpResponse = Page.Response;
    httpResponse.AppendHeader("Content-Disposition","attachment;filename="+HttpUtility.UrlEncode(FileName,System.Text.Encoding.UTF8));
    httpResponse.ContentEncoding=System.Text.Encoding.GetEncoding("GB2312");
    httpResponse.ContentType = FileType;
    StringBuilder ckpw = new StringBuilder(esql);
    System.IO.StringWriter  tw = new System.IO.StringWriter(ckpw) ;
    string filePath = Server.MapPath("..")+"\\"+FileName;
    System.IO.StreamWriter sw = System.IO.File.CreateText(filePath);
    sw.Write(tw.ToString());
    sw.Close();

    DownFile(httpResponse,FileName,filePath);
    httpResponse.End();
   }
   catch (Exception ee)
   {
    throw ee;
   }    
  }


//输出到前台  
private  bool DownFile(System.Web.HttpResponse Response,string fileName,string fullPath)
  {
   try
   {
    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(fullPath);
    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(fullPath);
    return true;
   }
   catch
   {
    return false;
   }
  }