我有一个带VB.NET的.aspx页面,在此页面中,我仅运行查询并创建和导出Excel文件。在代码的某些部分中,我尝试执行任何JS代码(警报,console.log等),并且尝试了不同的方式,例如:
但以上选项均无效。
我后面的代码是这样的:
Public Sub btnSubmit_Click(sender As Object, e As EventArgs) Handles btnSubmit.Click
Try
CreateExcel()
Catch ex as Exception
Finally
'' Kill other process
End Try
End Sub
Public Sub CreateExcel()
'' Do a lot of things for example run a query, open a write on an Excel file, etc...
'' This function has a lot of importance I will explain why below
DownloadReport(oExcel, "MyExcelFile.xlsx", Response)
Response.Write("<script type='text/javascript'>console.log('Hello 0');</script>")
End Sub
重要:逐步调试我的代码,我发现如果删除或注释DownloadReport行,我的JS代码就会执行,因此我几乎可以确定问题出在此功能上。
DownloadReport代码:
Public Sub DownloadReport(ByVal app As Microsoft.Office.Interop.Excel.Application, ByVal Filename As String, ByRef Response As HttpResponse)
Response.Write("<script type='text/javascript'>console.log('Hello 1');</script>")
Dim bytesInStream As Byte() = GetActiveWorkbook(app)
'' I know that Response.Clear deletes the above Response.Write
Response.Clear()
'' If I comment the above lines the Js on Response.Write also works
Response.AddHeader("Content-Disposition", "attachment; filename=" & Filename)
Response.AddHeader("Content-Length", (bytesInStream.Length))
Response.ContentType = "application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
Response.BinaryWrite(bytesInStream)
HttpContext.Current.ApplicationInstance.CompleteRequest()
Response.Write("<script type='text/javascript'>console.log('Hello 2');</script>")
End Sub
如果我在控制台上评论DownloadReport,我会看到Hello 0。
如果我在控制台上对DownloadReport函数的5行进行注释,则可以看到Hello 2和Hello 0的顺序。
如果我不发表任何评论,我将在控制台上看不到任何内容,也没有js错误消息。
我的代码有什么问题,我该如何解决?
答案 0 :(得分:0)
标头"Content-Disposition:attachment; filename=filename"
告诉您的浏览器将响应另存为文件,而不是将其呈现为HTML。
在文本编辑器中打开下载的文件,您将在末尾看到script
标签。