单击按钮下载 ASP.NET Excel 文件 [英] ASP.NET Excel file download on button click
问题描述
作为序言,所有这些都发生在本地 Intranet 上,它在任何时候都不需要连接到 Internet.
To preface, all of this occurs on a local intranet, which does not at any point need to connect to the internet.
我有一个运行查询的数据库,然后用户按下下载电子表格"按钮来创建/发送电子表格.电子表格的创建工作正常,但经过多次尝试后,我无法下载文件.这是我尝试过的:
I have a database on which I run a query, after which the user presses a "Download Spreadsheet" button which creates/sends the spreadsheet. The creation of the spreadsheet works fine, but after many attempts I cannot get the file to download. Here's what I've tried:
- 修改响应/标头对象
- 传输文件
- 写入文件
- 二进制流
- 重定向
- Response.Write(javascript 代码)
在大多数情况下,结果是创建了excel文件,但没有发生重定向/下载.在 Response.Redirect() 的情况下,如果它是一个网站,它工作得很好,但如果它重定向到 file:///,那么它会抛出一个线程异常,但没有更多细节.
In most cases, the result is that the excel file is created, but no redirect/download occurs. In the case of Response.Redirect(), if it's a website it works great, but if it's a redirect to a file:///, then it throws a thread exception but no more detail.
我怀疑这与 ASP.NET 文档的生命周期有关,但恐怕我对 ASP.NET 的经验不足,无法确定.
I suspect it has to do with the lifecycle of an ASP.NET document, but I'm afraid I am not experienced enough with ASP.NET to be able to know for sure.
推荐答案
FileInfo file = new FileInfo(PathToExcelFile); if (file.Exists) { Response.Clear(); Response.ClearHeaders(); Response.ClearContent(); Response.AddHeader("content-disposition", "attachment; filename=" + fileName); Response.AddHeader("Content-Type", "application/Excel"); Response.ContentType = "application/vnd.xls"; Response.AddHeader("Content-Length", file.Length.ToString()); Response.WriteFile(file.FullName); Response.End(); } else { Response.Write("This file does not exist."); }
这篇关于单击按钮下载 ASP.NET Excel 文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!