ASP.NET实现下载功能,直接向页面输出,;代码中以导出Excel为例
前台代码:
<input id="btnExportExcel" runat="server" type="button" value="导出Excel" onserverclick="btn_Action_expExcel" />
后台代码:
protected void btn_Action_expExcel(object sender, EventArgs e)
{
string filepath = Server.MapPath("~/Report/ReportXls//Test.xls");
Response.Clear();
Response.ContentType = "application nd.ms-excel";
Response.ContentEncoding = System.Text.Encoding.UTF8;
Response.Charset = "";
Response.AppendHeader("Content-Disposition", "attachment; filename=" +System.Web.HttpUtility.UrlEncode("文件下载测试", System.Text.Encoding.UTF8) + ".xls");
Response.WriteFile(filepath);//filepath代表文件路径
Response.Flush();
}
显示的文件名可以随便定义,不一定要和源文件名一样
filepath代表文件路径
还有一种方式就是通过字节流去向前台输入,关键代码如下:其他代码同上
byte[] f = System.IO.File.ReadAllBytes("E:\\exp.xls");
foreach (byte b in f)
{
Response.Write(b);
}
此处可以直接用字节流