ASP.点击.NET Excel文件下载按钮
本文关键字:文件下载 按钮 Excel NET 点击 ASP | 更新日期: 2023-09-27 18:04:03
作为开场白,所有这些都发生在本地内部网上,它在任何时候都不需要连接到internet。
我有一个数据库,我运行一个查询,之后用户按下"下载电子表格"按钮,创建/发送电子表格。电子表格的创建工作正常,但经过多次尝试后,我无法下载该文件。以下是我尝试过的:
- 修改响应/报头对象
- TransmitFile
- WriteFile
- BinaryStream
- Javascript重定向
- 反应。写(javascript代码)
在大多数情况下,结果是创建了excel文件,但没有发生重定向/下载。在Response.Redirect()的情况下,如果它是一个网站,它工作得很好,但如果它是一个重定向到一个文件:///,那么它抛出一个线程异常,但没有更多的细节。
我怀疑这与ASP的生命周期有关。. NET文档,但恐怕我没有足够的经验。
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.");
}
Response.Clear();
Response.Buffer = true;
Response.AddHeader("content-disposition", "attachment;filename=Academicprofileexcel.xls");
Response.Charset = "";
Response.ContentType = "application/vnd.ms-excel";
using (StringWriter sw = new StringWriter())
{
HtmlTextWriter hw = new HtmlTextWriter(sw);
//To Export all pages
Gridview1.AllowPaging = false;
this.getdetails();
Gridview1.HeaderRow.BackColor = Color.White;
foreach (TableCell cell in Gridview1.HeaderRow.Cells)
{
cell.BackColor = Gridview1.HeaderStyle.BackColor;
}
foreach (GridViewRow row in Gridview1.Rows)
{
row.BackColor = Color.White;
foreach (TableCell cell in row.Cells)
{
if (row.RowIndex % 2 == 0)
{
cell.BackColor = Gridview1.AlternatingRowStyle.BackColor;
}
else
{
cell.BackColor = Gridview1.RowStyle.BackColor;
}
cell.CssClass = "textmode";
}
}
Gridview1.RenderControl(hw);
//style to format numbers to string
string style = @"<style> .textmode { } </style>";
Response.Write(style);
Response.Output.Write(sw.ToString());
Response.Flush();
Response.End();
}
ClientScript.RegisterStartupScript(GetType(), "hwa", "window.open('" + System.Configuration.ConfigurationManager.AppSettings["WebSite"].ToString() + "Document/SummaryReport/" + FileName + "','_blank');", true);
表示代码是Excel文件下载上的按钮点击。所以现在很容易下载excel文件使用c#代码。