【问题标题】:Excel download not happening from serverExcel下载未从服务器发生
【发布时间】:2021-02-26 05:49:50
【问题描述】:

我试图通过单击按钮从服务器下载 Excel 文件,但它没有发生。它只是执行代码,但没有进行下载。

Protected Sub btn_dwnldexcel_Click(sender As Object, e As EventArgs) Handles btn_dwnldexcel.Click
        Dim fileToDownload = Server.MapPath("./Data/nd_format.xls")
        ''Response.ContentType = "application/octet-stream"
        Response.ContentType = "application/vnd.ms-excel"
        Dim cd = New ContentDisposition()
        cd.Inline = False
        cd.FileName = Path.GetFileName(fileToDownload)
        Response.AppendHeader("Content-Disposition", cd.ToString())
        Dim fileData As Byte() = System.IO.File.ReadAllBytes(fileToDownload)
        Response.OutputStream.Write(fileData, 0, fileData.Length)
End Sub

任何想法都将不胜感激。

【问题讨论】:

  • 你是在 Visual Studio 中运行它吗?您是否尝试在调试模式下单步执行以查看问题出在哪里?请阅读stackoverflow.com/help/how-to-ask;本网站的目的不是为您调试代码。

标签: asp.net vb.net


【解决方案1】:

与其尝试从同一页面发送数据,不如使用通用处理程序,它没有处理 aspx 页面的开销。

因此,如果您向项目添加新项目并找到“通用处理程序 (.ashx)”(或类似),并使用如下代码:

Imports System.Web
Imports System.Web.Services
Imports System.IO

Public Class DownloadExcelFile
    Implements System.Web.IHttpHandler

    Sub ProcessRequest(ByVal context As HttpContext) Implements IHttpHandler.ProcessRequest

        Dim actualFile = Server.MapPath("~/Data/nd_format.xls")

        If File.Exists(actualFile) Then
            context.Response.ContentType = "application/octet-stream"
            context.Response.AddHeader("content-disposition", "attachment; filename=""" & Path.GetFileName(actualFile) & """")
            context.Response.TransmitFile(actualFile)

        Else
            context.Response.Clear()
            context.Response.TrySkipIisCustomErrors = True
            context.Response.StatusCode = 404
            context.Response.Write("<html><head><title>File not found</title><style>body {font-family: Arial,sans-serif;}</style></head><body><h1>File not found</h1><p>Error.</p></body></html>")
            context.Response.End()

         End If

    End Sub

    ReadOnly Property IsReusable() As Boolean Implements IHttpHandler.IsReusable
        Get
            Return False
        End Get
    End Property

End Class

然后你可以使用超链接而不是按钮:

<a href="DownloadExcelFile.ashx">Download Excel File</a>

(如果需要,您可以使用 CSS 将超链接设置为按钮。)

【讨论】:

    猜你喜欢
    • 2013-06-07
    • 1970-01-01
    • 1970-01-01
    • 2015-09-10
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-02
    • 1970-01-01
    相关资源
    最近更新 更多