asp.net中Exce文件下载
先试用Response.WriteFile的方法:
FileInfo fi = new FileInfo(excelFile);//excelFile为文件在服务器上的地址 HttpResponse contextResponse = HttpContext.Current.Response; contextResponse.Clear(); contextResponse.Buffer = true; contextResponse.Charset = "GB2312"; //设置了类型为中文防止乱码的出现 contextResponse.AppendHeader("Content-Disposition", String.Format("attachment;filename={0}", excelName)); //定义输出文件和文件名 contextResponse.AppendHeader("Content-Length", fi.Length.ToString()); contextResponse.ContentEncoding = Encoding.Default; contextResponse.ContentType = "application/ms-excel";//设置输出文件类型为excel文件。 contextResponse.WriteFile(fi.FullName); contextResponse.Flush(); contextResponse.End();
分段下载:
private bool DownFile(HttpResponse response,string filename,string fullpath) { try { response.ContentType = "application/octet-stream";//"application/octet-stream"; response.AppendHeader("content-disposition", "attachment;filename=" + System.Web.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(); return true; } catch { return false; } }