Jack-Leung

  博客园  :: 首页  :: 新随笔  :: 联系 :: 订阅 订阅  :: 管理

网络上搜索,一大堆废话,以下为简单的导出生成Excel代码:

string excelFile = Server.MapPath("~/SB/UpFile/20151104111008/BoxTag.xls");//文件服务器地址
string excelName = "BoxTag.xls";//客户端保存文件名称和类型
FileInfo fi = new FileInfo(excelFile);//excelFile为文件在服务器上的地址
HttpResponse contextResponse = HttpContext.Current.Response;
contextResponse.Redirect(string.Format("~/SB/UpFile/20151104111008/{0}", "BoxTag.xls"), false);
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();

fi.Delete(); //避免文件占用


//contextResponse.End();

HttpContext.Current.ApplicationInstance.CompleteRequest();

如上所示,比正常生成导出Excel只多了一行代码:

contextResponse.Redirect(string.Format("~/SB/UpFile/20151104111008/{0}", "BoxTag.xls"), false);

因为迅雷捕捉的是最后一次URL发送链接,采用最简单的解决方法:Response.Redirect(),转向实际文件地址。但这样相当于告知客户端用户文件的实际地址,隐私性不佳。

 

posted on 2015-11-04 15:03  Jack.leung  阅读(1396)  评论(0编辑  收藏  举报