ASP.NET 按钮点击下载 Excel 文件

5

首先声明,所有操作都在本地内部网络中进行,不需要连接互联网。

我有一个数据库,在其中运行查询后,用户点击“下载电子表格”按钮来创建/发送电子表格。电子表格的创建工作正常,但是经过多次尝试,我无法使文件下载。以下是我尝试过的方法:

  • 修改Response/Header对象
    • TransmitFile
    • WriteFile
    • BinaryStream
    • Redirect
  • Javascript重定向
    • Response.Write(javascript代码)

在大多数情况下,结果是Excel文件已创建,但没有重定向/下载发生。在使用Response.Redirect()时,如果是网站,则非常有效,但如果是重定向到file:///,则会抛出线程异常,但没有更多详细信息。

我怀疑这与ASP.NET文档的生命周期有关,但恐怕我对ASP.NET的经验不足,无法确定。


你的响应中ContentType是否设置为application/vnd.ms-excel? - FlyingStreudel
你正在使用哪个版本的ASP.NET/.NET框架? - Shane Wealti
是的,关于内容类型,.NET 4。 - Itskiddly
3个回答

18
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.End() 会抛出线程中止错误。 - Itskiddly
嗯...这是我从一个运行良好的生产系统中复制的代码。我不知道为什么它对你不起作用。我会尝试弄清楚在 Response.End() 发生了什么。 - Shane Wealti
1
使用 CompleteRequest 方法确实避免了错误,但是没有下载任何文件。 - Itskiddly

1
            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();
            }

-2
ClientScript.RegisterStartupScript(GetType(), "hwa", "window.open('" + System.Configuration.ConfigurationManager.AppSettings["WebSite"].ToString() + "Document/SummaryReport/" + FileName + "','_blank');", true);

这段代码是在按钮点击时下载Excel文件。现在使用C#代码轻松下载您的Excel文件。


1
你能详细说明一下你的答案吗?仅仅发布代码是不够的。 - Noel Widmer

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接